poj 1201 差分约束+spfa
非常经典的差分约束系统的建模。求最小值需要转化为求最长路。
1 #include <algorithm> 2 #include <iostream> 3 #include <cstring> 4 #include <cstdio> 5 using namespace std; 6 7 const int INF = 99999999; 8 const int N = 50002; 9 const int M = 200000; 10 int head[N]; 11 int dist[N]; 12 bool visit[N]; 13 int n, m, e; 14 int maxn, minn; 15 16 struct Edge 17 { 18 int v, next, w; 19 } edge[M]; 20 21 void addEdge( int u, int v, int w ) 22 { 23 edge[e].v = v; 24 edge[e].w = w; 25 edge[e].next = head[u]; 26 head[u] = e++; 27 } 28 29 void spfa( int s ) 30 { 31 for ( int i = minn; i <= maxn; i++ ) 32 { 33 dist[i] = -INF; 34 visit[i] = false; 35 } 36 dist[s] = 0; 37 visit[s] = true; 38 int q[N], top = 0; 39 q[top++] = s; 40 while ( top ) 41 { 42 int u = q[--top]; 43 visit[u] = false; 44 for ( int j = head[u]; j != -1; j = edge[j].next ) 45 { 46 int v = edge[j].v, w = edge[j].w; 47 if ( dist[v] < dist[u] + w ) 48 { 49 dist[v] = dist[u] + w; 50 if ( !visit[v] ) 51 { 52 q[top++] = v; 53 visit[v] = true; 54 } 55 } 56 } 57 } 58 } 59 60 int main () 61 { 62 while ( scanf("%d", &n) != EOF ) 63 { 64 e = 0; 65 memset( head, -1, sizeof(head) ); 66 minn = INF, maxn = -INF; 67 for ( int i = 1; i <= n; i++ ) 68 { 69 int a, b, c; 70 scanf("%d%d%d", &a, &b, &c); 71 addEdge( a, b + 1, c ); 72 maxn = max( maxn, b + 1 ); 73 minn = min( minn, a ); 74 } 75 for ( int i = minn + 1; i <= maxn; i++ ) 76 { 77 addEdge( i, i - 1, -1 ); 78 addEdge( i - 1, i, 0 ); 79 } 80 spfa(minn); 81 printf("%d\n", dist[maxn]); 82 } 83 return 0; 84 }