写的好搓啊。。新年第一水。
View Code
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 #define maxn 510 6 #define maxm 2710 7 using namespace std; 8 int v[maxm],w[maxm],next[maxm]; 9 int first[maxn],inq[maxn],cnt[maxn],d[maxn]; 10 int e,V,E; 11 12 void init() 13 { 14 memset(first,-1,sizeof(first)); 15 memset(next,0,sizeof(next)); 16 } 17 18 void Read_Graph() 19 { 20 int a,b,c; 21 e = 0; 22 for(int i = 0;i < E;i++) 23 { 24 scanf("%d%d%d",&a,&b,&c); 25 v[e] = b; 26 next[e] = first[a]; 27 first[a] = e; 28 w[e] = c; 29 e++; 30 } 31 } 32 33 bool negativeCycle() 34 { 35 queue<int> q; 36 memset(cnt,0,sizeof(cnt)); 37 memset(inq,0,sizeof(inq)); 38 int i; 39 for(i = 1;i <= V;i++) 40 { 41 d[i] = 0; 42 q.push(i); 43 } 44 45 inq[1] = 1; 46 47 while(!q.empty()) 48 { 49 int ith = q.front(); 50 q.pop(); 51 inq[ith] = 0; 52 for(i = first[ith];i != -1;i = next[i]) 53 { 54 if(d[v[i]] > d[ith] + w[i]) 55 { 56 d[v[i]] = d[ith] + w[i]; 57 if(!inq[v[i]]) 58 { 59 inq[v[i]] = 1; 60 q.push(v[i]); 61 if(++cnt[v[i]] > V) return true; 62 } 63 } 64 } 65 } 66 return false; 67 } 68 69 bool test(int x) 70 { 71 int i; 72 bool ret; 73 for(i = 0;i < e;i++) 74 w[i] -= x; 75 ret = negativeCycle(); 76 for(i = 0;i < e;i++) 77 w[i] += x; 78 return ret; 79 } 80 81 void solve() 82 { 83 if(test(0)) 84 { 85 printf("No Solution\n"); 86 return; 87 } 88 if(!test(10001)) 89 { 90 printf("Infinite\n"); 91 return; 92 } 93 int l = 1,r = 10000,mid; 94 while(l < r) 95 { 96 mid = (l + r) >> 1; 97 if(test(mid)) r = mid; 98 else l = mid + 1; 99 } 100 l--; 101 if(l == 0) printf("No Solution\n"); 102 else printf("%d\n",l); 103 } 104 int main() 105 { 106 while(scanf("%d%d",&V,&E) == 2) 107 { 108 init(); 109 Read_Graph(); 110 solve(); 111 } 112 return 0; 113 }