http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2770
題意:陸遜準備燒劉備的連營,現在已經打探到劉備有n個營地排成一條線,編號1到n,每個營地有一個人數上限Ci。他還打探到了m條情報,每條情報包括i,j,k三個數字,表示從i營到j營的人數至少有k個。現在讓你根據情報求出劉備所以的營地加起來最少有多少個士兵。有可能情報有誤導致無解,輸出"Bad Estimations"。
思路:設S[i]爲前i個營地的人數,對於每條情報(i,j,k)可以得到不等式S[j] - S[i - 1] >= k。
由營地人數上限Ci可得不等式 0 <= S[i] - S[i - 1] <= C[i],即S[i] - S[i - 1] <= C[i] 和 S[i] - S[i - 1] >= 0。
總人數即S[n] = S[n] - S[0],題目要求最小值,建立差分約束系統求最長路即可。用鏈式前向星建圖,spfa判負環。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#include <list>
#include <cstdlib>
#include <set>
#include <string>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
int n, m, c[maxn];
struct edg{
int v, d, nxt;
}G[20005];
int pre[maxn], tot, dis[maxn], times[maxn];
bool vis[maxn];
void add(int u, int v, int w) {
G[tot].v = v;
G[tot].d = w;
G[tot].nxt = pre[u];
pre[u] = tot++;
}
int spfa(int s, int e) {
memset(vis, 0, sizeof(vis));
memset(times, 0, sizeof(times));
for (int i = 1; i <= n; ++i) {
dis[i] = -inf;
}
vis[s] = 1;
dis[s] = 0;
times[s] = 1;
queue<int> que;
que.push(s);
while (!que.empty()) {
int u = que.front();
que.pop();
vis[u] = false;
for (int i = pre[u]; ~i; i = G[i].nxt) {
int v = G[i].v, w = G[i].d;
if (dis[u] + w > dis[v]) {
dis[v] = dis[u] + w;
if (!vis[v]) {
vis[v] = 1;
if (++times[v] > n) {
return -1;
}
que.push(v);
}
}
}
}
return dis[n];
}
int main(){
int u, v, w;
while (~scanf("%d%d", &n, &m)) {
memset(pre, -1, sizeof(pre));
tot = 0;
for (int i = 1; i <= n; ++i){
scanf("%d", &c[i]);
add(i, i - 1, -c[i]);
add(i - 1, i, 0);
}
while (m--) {
scanf("%d%d%d", &u, &v, &w);
add(u - 1, v, w);
}
int ans = spfa(0, n);
if (ans == -1) {
puts("Bad Estimations");
} else {
printf("%d\n", ans);
}
}
return 0;
}