就是钱换钱,能否使钱增多。最短路径正权回路判断。我用的是bellman_ford.
代码:
1 #include<iostream>
2 #include<cstdio>
3 #include<map>
4 #include<string>
5 using namespace std;
6
7 struct node
8 {
9 int from,to;
10 double rate;
11 }e[901];
12
13 map<string,int> id;
14 double dis[31];
15 int money,exchange;
16 bool bellman_ford();
17
18 int main()
19 {
20 string s,s1,s2;
21 double r;
22 int i,j,c;
23 c = 0;
24 while(scanf("%d",&money) && money)
25 {
26 for(i = 1 ; i <= money ; ++i)
27 {
28 cin>>s;
29 id[s] = i;
30 }
31 scanf("%d",&exchange);
32 for(i = 1 ; i <= exchange ; ++i)
33 {
34 cin>>s1>>r>>s2;
35 e[i].from = id[s1];
36 e[i].to = id[s2];
37 e[i].rate = r;
38 }
39 printf("Case %d: ",++c);
40 if(bellman_ford())
41 printf("Yes\n");
42 else
43 printf("No\n");
44 id.clear();
45 }
46
47 return 0;
48 }
49
50 bool bellman_ford()
51 {
52 double temp;
53 int i,j;
54 bool flag;
55 for(i = 2 ;i <= money ; ++i)
56 dis[i] = 0;
57 dis[1] = 1.0;
58 for(i = 0 ; i < money ; ++i)
59 {
60 flag = true;
61 for(j = 1 ; j <= exchange ; ++j)
62 {
63 temp = e[j].rate*dis[e[j].from];
64 if(temp > dis[e[j].to] )
65 {
66 dis[e[j].to] = temp;
67 flag = false;
68 }
69
70 }
71 if( flag )
72 break;
73 }
74
75 if(i == money )
76 return true;
77 return false;
78 }