同样是套汇问题,这题要简单些,我为了多练,换成Floyd算法了。Floyd最大的优点就是写起来简单。

 1 #include <stdio.h>
 2 #include <string.h>
 3 int m,n,cas=1;
 4 char name[35][40];
 5 double rate[30][30];
 6 int find(char *s)
 7 {
 8     for(int i = 0; i < n; i++)
 9         if(!strcmp(s,name[i]))
10             return i;
11     return -1;
12 }
13 bool Floyd()
14 {
15     int i,j,k;
16     for(k = 0; k < n; k++)
17         for(i = 0; i < n; i++)
18             for(j = 0; j < n; j++)
19                 if(rate[i][k] * rate[k][j] > rate[i][j])
20                     rate[i][j] = rate[i][k] * rate[k][j];
21     return (rate[0][0] > 1) ?1 :0 ;
22 }
23 int main()
24 {
25     int i;
26     char t1[40],t2[40];
27     double r;
28     while(scanf("%d",&n),n)
29     {
30         memset(rate,0,sizeof(rate));
31         for(i = 0; i < n; i++)
32             scanf("%s",name[i]);
33         scanf("%d",&m);
34         for(i = 0; i < m; i++)
35         {
36             scanf("%s%lf%s",t1,&r,t2);
37             rate[find(t1)][find(t2)] = r;
38         }
39         if(Floyd())
40             printf("Case %d: Yes\n",cas++);
41         else printf("Case %d: No\n",cas++);
42     }
43     return 0;
44 }