UVA 11090 Going in Cycle!!
View Code
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 #include <vector> 6 #define maxn 60 7 using namespace std; 8 vector<int> v,next; 9 vector<double> w; 10 double d[maxn]; 11 int first[maxn],inq[maxn],cnt[maxn]; 12 int n,m,e,ub; 13 14 void init() 15 { 16 ub = 0; 17 e = 0; 18 v.clear(); 19 w.clear(); 20 next.clear(); 21 memset(first,-1,sizeof(first)); 22 } 23 24 void Read_Graph() 25 { 26 int i,a,b,c; 27 for(i = 0;i < m;i++) 28 { 29 scanf("%d%d%d",&a,&b,&c); 30 ub = max(ub,c); 31 w.push_back(c); 32 v.push_back(b); 33 next.push_back(first[a]); 34 first[a] = e; 35 e++; 36 } 37 } 38 39 bool negativeCycle() 40 { 41 queue<int> q; 42 memset(cnt,0,sizeof(cnt)); 43 memset(inq,0,sizeof(inq)); 44 int i; 45 for(i = 1;i <= n;i++) 46 { 47 q.push(i); 48 d[i] = 0; 49 } 50 inq[1] = 1; 51 while(!q.empty()) 52 { 53 int ith = q.front(); 54 q.pop(); 55 inq[ith] = 0; 56 for(i = first[ith];i != -1;i = next[i]) 57 { 58 if(d[v[i]] > d[ith] + w[i]) 59 { 60 d[v[i]] = d[ith] + w[i]; 61 if(!inq[v[i]]) 62 { 63 q.push(v[i]); 64 inq[v[i]] = 1; 65 if(++cnt[v[i]] > n) return true; 66 } 67 } 68 } 69 } 70 return false; 71 } 72 73 bool test(double x) 74 { 75 int i; 76 bool ret; 77 for(i = 0;i < e;i++) 78 w[i] -= x; 79 ret = negativeCycle(); 80 for(i = 0;i < e;i++) 81 w[i] += x; 82 return ret; 83 } 84 85 int main() 86 { 87 int N; 88 scanf("%d",&N); 89 for(int ncase = 1;ncase <= N;ncase++) 90 { 91 scanf("%d%d",&n,&m); 92 init(); 93 Read_Graph(); 94 double middle,left = 0,right = ub; 95 if(!test(ub + 1)) 96 { 97 printf("Case #%d: No cycle found.\n",ncase); 98 continue; 99 } 100 while(right - left > 1e-3) 101 { 102 middle = left + (right - left) / 2; 103 if(test(middle)) right = middle; 104 else left = middle; 105 } 106 printf("Case #%d: %.2f\n",ncase,left); 107 } 108 return 0; 109 }