pku2240 Arbitrage

http://poj.org/problem?id=2240

图论,最短路,SPFA

  1 #include <stdio.h>
  2 #include <string.h>
  3 #include <queue>
  4 #include <string>
  5 #include <map>
  6 #include <iostream>
  7 
  8 #define N 123
  9 
 10 using namespace std;
 11 
 12 int n, m, src;
 13 int x[N], y[N], len[N];
 14 float dist[N];
 15 bool inQue[N];
 16 queue<int> que;
 17 const int inf = 1<<30;
 18 vector<pair<int, float> > g[N];
 19 int count1[N];
 20 float src0 = 10000;
 21 
 22 int spfa()
 23 {
 24     int i;
 25     for(i=0; i<N; i++)
 26     {
 27         inQue[i] = false;
 28         dist[i] = 0;
 29         count1[i] = 0;
 30     }
 31     dist[src] = src0;
 32     while(!que.empty())
 33     {
 34         que.pop();
 35     }
 36     que.push(src);
 37     count1[src] ++;
 38     inQue[src] = true;
 39     while(!que.empty())
 40     {
 41         int u = que.front();
 42         que.pop();
 43         for(i=0; i<g[u].size(); i++)
 44         {
 45             if(dist[u]*g[u][i].second > dist[g[u][i].first])
 46             {
 47                 dist[g[u][i].first] = dist[u]*g[u][i].second;
 48                 if(!inQue[g[u][i].first])
 49                 {
 50                     inQue[g[u][i].first] = true;
 51                     que.push(g[u][i].first);
 52                     count1[g[u][i].first] ++;
 53                     if(count1[g[u][i].first] > n)
 54                     {
 55                         return -1;
 56                     }
 57                 }
 58             }
 59         }
 60         inQue[u] = false;
 61     }
 62     return 0;
 63 }
 64 
 65 
 66 int main()
 67 {
 68     int x, y, cases, i, j;
 69     float len;
 70     map<string, int> map1;
 71     string s, s1, s2;
 72     for(cases=1; cin >> n, n; cases++)
 73     {
 74         printf("Case %d: ", cases);
 75         map1.clear();
 76         for(i=1; i<=n; i++)
 77         {
 78             g[i].clear();
 79             cin >> s;
 80             map1.insert(make_pair(s, i));
 81         }
 82         cin >> m;
 83         for(i=1; i<=m; i++)
 84         {
 85             cin >> s1 >> len >> s2;
 86             x = map1[s1];
 87             y = map1[s2];
 88             g[x].push_back(make_pair(y, len));
 89         }
 90         src = 1;
 91         if(spfa() == -1)
 92         {
 93             printf("Yes\n");
 94         }
 95         else
 96         {
 97             if(dist[1] > 10000.0)
 98             {
 99                 printf("Yes\n");
100             }
101             else
102             {
103                 printf("No\n");
104             }
105         }
106     }
107     return 0;
108 }

 

posted @ 2013-05-25 11:25  Yuan1991  阅读(122)  评论(0)    收藏  举报