POJ2240 Arbitrage(Floyd判负环)

跑完Floyd后,d[u][u]就表示从u点出发可以经过所有n个点回到u点的最短路,因此只要根据数组对角线的信息就能判断是否存在负环。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<string>
 5 #include<algorithm>
 6 using namespace std;
 7 
 8 int n;
 9 double d[33][33];
10 void Floyd(){
11     for(int k=0; k<n; ++k){
12         for(int i=0; i<n; ++i){
13             for(int j=0; j<n; ++j) d[i][j]=max(d[i][j],d[i][k]*d[k][j]);
14         }
15     }
16 }
17 bool isYes(){
18     for(int i=0; i<n; ++i){
19         if(d[i][i]>1) return 1;
20     }
21     return 0;
22 }
23 int main(){
24     int t=0,m;
25     string name[33],s1,s2;
26     double c;
27     while(cin>>n && n){
28         for(int i=0; i<n; ++i) cin>>name[i];
29         sort(name,name+n);
30         memset(d,0,sizeof(d));
31         cin>>m;
32         while(m--){
33             cin>>s1>>c>>s2;
34             d[lower_bound(name,name+n,s1)-name][lower_bound(name,name+n,s2)-name]=c;
35         }
36         Floyd();
37         if(isYes()) printf("Case %d: Yes
",++t);
38         else printf("Case %d: No
",++t);
39     }
40     return 0;
41 }
原文地址:https://www.cnblogs.com/WABoss/p/5093378.html