bellmanford最长路判正环
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 13947 | Accepted: 5876 |
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
Source
#include <iostream> #include <cstdio> #include <cstring> #include <map> #include <cmath> #include <algorithm> using namespace std; const double eps=1e-8; double g[120][120]; int n,m; double dist[120]; map<string,int> mp; bool Bellman_Ford() { memset(dist,0,sizeof(dist)); dist[0]=1; for(int i=0;i<n-1;i++) { bool flag=false; for(int j=0;j<n;j++) { for(int k=0;k<n;k++) { if(fabs(g[j][k])>eps) { if(dist[k]<dist[j]*g[j][k]) { flag=true; dist[k]=dist[j]*g[j][k]; } } } } if(!flag) return false; } bool flag=false; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(dist[i]<dist[j]*g[j][i]) { flag=true; } if(flag) break; } if(flag) break; } return flag; } int main() { int cas=1; while(scanf("%d",&n)!=EOF&&n) { mp.clear(); for(int i=0;i<n;i++) { string name; cin>>name; mp[name]=i; } memset(g,0,sizeof(g)); scanf("%d",&m); while(m--) { string name1,name2; double rate; cin>>name1>>rate>>name2; g[mp[name1]][mp[name2]]=rate; } printf("Case %d: ",cas++); if(Bellman_Ford()) puts("Yes"); else puts("No"); } return 0; }