题目链接:http://poj.org/problem?id=3169
很好的差分约束入门题目,自己刚看时学呢
代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 #include<queue> 6 using namespace std; 7 #define INF 0x3f3f3f3f 8 #define maxn 1010 9 int dis[maxn]; 10 int path[maxn]; 11 int inq[maxn]; 12 int cnt[maxn]; 13 class node 14 { 15 public: 16 int to; 17 int w; 18 int next; 19 }; 20 node edge[maxn*10]; 21 int head[maxn*3]; 22 int tol; 23 int n,ML,MD; 24 void add(int u,int v,int w) 25 { 26 edge[tol].to=v; 27 edge[tol].w =w; 28 edge[tol].next=head[u]; 29 head[u]=tol++; 30 }; 31 queue<int>Q; 32 bool SPFA() 33 { 34 memset(inq,0,sizeof(inq)); 35 memset(cnt,0,sizeof(cnt)); 36 int v0=1; 37 for(int i=1;i<=n;i++) 38 { 39 dis[i]=INF; 40 path[i]=v0; 41 inq[i]=0; 42 } 43 dis[v0]=0; 44 path[v0]=v0; 45 inq[v0]++; 46 cnt[v0]++; 47 Q.push(v0); 48 while(!Q.empty()) 49 { 50 int u=Q.front(); 51 Q.pop(); 52 inq[u]--; 53 int tmp=head[u]; 54 55 56 while(tmp!=-1) 57 { 58 int v=edge[tmp].to; 59 int w=edge[tmp].w; 60 if(dis[v]>dis[u]+w) 61 { 62 dis[v]=dis[u]+w; 63 path[v]=u; 64 if(inq[v]==0) 65 { 66 inq[v]++; 67 if(++cnt[v]>n) return false; 68 Q.push(v); 69 70 } 71 } 72 tmp=edge[tmp].next; 73 } 74 } 75 return true; 76 } 77 int main() 78 { 79 int a,b,d; 80 while(scanf("%d%d%d",&n,&ML,&MD)!=EOF) 81 { 82 tol=0; 83 memset(head,-1,sizeof(head)); 84 while(ML--) 85 { 86 scanf("%d%d%d",&a,&b,&d); 87 add(a,b,d); 88 89 } 90 while(MD--) 91 { 92 scanf("%d%d%d",&a,&b,&d); 93 add(b,a,-d); 94 } 95 if(!SPFA()) cout<<"-1"<<endl; 96 else 97 if(dis[n]>=INF) cout<<"-2"<<endl; 98 else cout<<dis[n]<<endl; 99 100 101 } 102 return 0; 103 }