zoj 1508 poj 1201 Intervals
差分约束系统。
#include<cstdio> #include<cstring> #include<cmath> #include<vector> #include<map> #include<queue> #include<algorithm> using namespace std; const int maxn = 50005; map<int, int> jz[maxn]; vector<int>ljb[maxn]; int dist[maxn],flag[maxn]; int mm, mx; void spfa() { int ii; queue<int>Q; memset(flag, 0, sizeof(flag)); flag[mx] = 1; for (ii = 0; ii <= mx; ii++) dist[ii] = 999999999; dist[mx] = 0; Q.push(mx); while (!Q.empty()) { int hh = Q.front(); Q.pop(); flag[hh] = 0; for (ii = 0; ii < ljb[hh].size(); ii++) { if (jz[hh][ljb[hh][ii]] != 999999999) { if (dist[hh] + jz[hh][ljb[hh][ii]] < dist[ljb[hh][ii]]) { dist[ljb[hh][ii]] = dist[hh] + jz[hh][ljb[hh][ii]]; if (flag[ljb[hh][ii]] == 0) { Q.push(ljb[hh][ii]); flag[ljb[hh][ii]] = 1; } } } } } } int main() { int i, n, a, b, c; while (~scanf("%d", &n)) { for (i = 0; i <= 50000; i++) jz[i].clear(); for (i = 0; i <= 50000; i++) ljb[i].clear(); mx = -999999999, mm = 999999999; for (i = 0; i < n; i++) { scanf("%d%d%d", &a, &b, &c); ljb[b].push_back(a - 1); jz[b][a - 1] = -c; if (a < mm) mm = a; if (b > mx) mx = b; } for (i = 1; i <= mx; i++) { ljb[i - 1].push_back(i); jz[i - 1][i] = 1; ljb[i].push_back(i - 1); jz[i][i - 1] = 0; } spfa(); printf("%d\n", dist[mx] - dist[mm - 1]); } return 0; }