又是套汇为题,初始化d数组为1就可以了,用bellman—ford算法。
1 #include<stdio.h> 2 #include<string.h> 3 4 int n, m, num, u[2000], v[2000]; 5 double w[2000], d[50], ra; 6 char s[50][100], s1[100], s2[100]; 7 8 void solve() 9 { 10 for(int i = 0; i <= n; i ++) d[i] = 1; 11 for(int k = 0; k < n-1; k ++) 12 for(int i = 0; i < m; i ++) 13 { 14 int x = u[i], y = v[i]; 15 if(d[y] < d[x]*w[i]) d[y] = d[x]*w[i]; 16 } 17 int flag = 0; 18 for(int i = 0; i < m; i++) 19 { 20 int x = u[i],y = v[i]; 21 if(d[y] < d[x]*w[i]) flag = 1; 22 } 23 if(flag == 1) printf("Case %d: Yes\n",num++); 24 else printf("Case %d: No\n",num++); 25 } 26 27 void init() 28 { 29 while(scanf("%d",&n)) 30 { 31 if(n == 0) break; 32 for(int i = 0; i < n; i ++) 33 scanf("%s",s[i]); 34 scanf("%d",&m); 35 for(int i = 0; i < m; i ++) 36 { 37 scanf("%s",s1); 38 scanf("%lf",&ra); 39 scanf("%s",s2); 40 int a, b; 41 for(int j = 0; j < n; j ++) 42 { 43 if(!strcmp(s[j], s1)) a = j; 44 if(!strcmp(s[j], s2)) b = j; 45 } 46 u[i] = a; 47 v[i] = b; 48 w[i] = ra; 49 } 50 solve(); 51 } 52 } 53 54 int main() 55 { 56 num = 1; 57 init(); 58 return 0; 59 }