I - Arbitrage

  1 //SPFA
  2 #include <iostream>
  3 #include <algorithm>
  4 #include <string>
  5 #include <map>
  6 #include <cstring>
  7 #include <vector>
  8 #include <queue>
  9 using namespace std;
 10 
 11 const int maxn = 50;
 12 const double Start = 100;
 13 
 14 struct node{
 15     int val;
 16     double len;
 17     node(int _val, double _len){
 18         val = _val;
 19         len = _len;
 20     };
 21 };
 22 
 23 map<string ,int>mp;
 24 vector<node>g[maxn];
 25 double d[maxn];
 26 bool vis[maxn];
 27 
 28 #define INF 0xffffff
 29 
 30 void init(int n, int x){
 31     for(int i = 0;i <= n;i++){
 32         d[i] = -INF;
 33         vis[i] = true;
 34     }
 35     d[x] = Start;
 36 }
 37 
 38 queue<int>q;
 39 bool SPFA(int s){
 40     while(!q.empty())
 41         q.pop();
 42     q.push(s);
 43     vis[s] = false;
 44     while(!q.empty()){
 45         int x = q.front();q.pop();
 46         int xl = g[x].size();
 47         for(int i = 0 ;i < xl; i++){
 48             node y = g[x][i];
 49             /*
 50             if(vis[y.val] == false){
 51                 continue;
 52             }
 53             vis[y.val] = true;
 54             */
 55             double k = d[x]*y.len;
 56             if(k > d[y.val]){
 57                 d[y.val] = k;
 58                 q.push(y.val);
 59             }
 60         }
 61         if(d[s] > Start){
 62             return true;
 63         }
 64     }
 65     return false;
 66 }
 67 
 68 int main(){
 69     int n;
 70     int cnt = 0;
 71     while(cin >> n){
 72         mp.clear();
 73         for(int i =0 ;i < maxn;i++){
 74             g[i].clear();
 75         }
 76         cnt++;
 77         if(n == 0)
 78             break;
 79         string s;
 80         for(int i = 1;i <= n;i++){
 81             cin >> s;
 82             mp[s] = i;
 83         }
 84         int m;
 85         cin >> m;
 86         string s1, s2;
 87         double d;
 88         for(int i = 0;i < m;i++){
 89             cin >> s1 >> d >> s2;
 90             int u = mp[s1];
 91             int v = mp[s2];
 92             g[u].push_back(node(v,d));
 93         }
 94 
 95         bool ok = false;
 96         for(int i = 1;i <= n;i++){
 97             init(n, i);
 98             if(SPFA(i)){
 99                 ok = true;
100                 break;
101             }
102         }
103         cout << "Case " << cnt << ": ";
104         if(ok){
105             cout << "Yes" << endl;
106         }
107         else{
108             cout << "No" << endl;
109         }
110     }
111     return 0;
112 }

猜你喜欢

转载自www.cnblogs.com/jaydenouyang/p/9073847.html