Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 17145 | Accepted: 7238 |
Description
Input
Output
Sample Input
3 USDollar BritishPound FrenchFranc 3 USDollar 0.5 BritishPound BritishPound 10.0 FrenchFranc FrenchFranc 0.21 USDollar 3 USDollar BritishPound FrenchFranc 6 USDollar 0.5 BritishPound USDollar 4.9 FrenchFranc BritishPound 10.0 FrenchFranc BritishPound 1.99 USDollar FrenchFranc 0.09 BritishPound FrenchFranc 0.19 USDollar 0
Sample Output
Case 1: Yes Case 2: No
对应关系用map来处理,然后判断是否存在正环。有一点感悟就是,从A -> B,若存在正环,那么A -> B再B -> A之后A的值就会被变大,再次更新再次变大。
1 #include <iostream> 2 #include <string> 3 #include <map> 4 #include <vector> 5 #include <queue> 6 #include <cstdio> 7 using namespace std; 8 9 const int INF = 0xffffff; 10 const int SIZE = 35; 11 int N,M; 12 double D[SIZE]; 13 struct Node 14 { 15 int from,to; 16 double cost; 17 }G[1000]; 18 map<string,int> mapstring; 19 20 bool Bellman_Ford(int); 21 bool relax(int,int,double); 22 int main(void) 23 { 24 string box,box_2; 25 double num; 26 int from,to; 27 int count = 0; 28 29 while(scanf("%d",&N) && N) 30 { 31 count ++; 32 for(int i = 1;i <= N;i ++) 33 { 34 cin >> box; 35 mapstring.insert(pair<string,int>(box,i)); 36 } 37 scanf("%d",&M); 38 for(int i = 0;i < M;i ++) 39 { 40 cin >> box >> num >> box_2; 41 G[i].from = mapstring[box]; 42 G[i].to = mapstring[box_2]; 43 G[i].cost = num; 44 } 45 bool flag = true; 46 for(int i = 1;i <= N;i ++) 47 if(!Bellman_Ford(i)) 48 { 49 printf("Case %d: Yes\n",count); 50 flag = false; 51 break; 52 } 53 if(flag) 54 printf("Case %d: No\n",count); 55 } 56 57 return 0; 58 } 59 60 bool Bellman_Ford(int s) 61 { 62 bool update; 63 fill(D,D + SIZE,0); 64 D[s] = INF; 65 66 for(int i = 0;i < N - 1;i ++) 67 { 68 update = false; 69 for(int j = 0;j < M;j ++) 70 if(relax(G[j].from,G[j].to,G[j].cost)) 71 update = true; 72 if(!update) 73 break; 74 } 75 for(int i = 0;i < M;i ++) 76 if(relax(G[i].from,G[i].to,G[i].cost)) 77 return false; 78 79 return true; 80 } 81 82 bool relax(int from,int to,double cost) 83 { 84 if(D[to] < D[from] * cost) 85 { 86 D[to] = D[from] * cost; 87 return true; 88 } 89 return false; 90 }