Arbitrage POJ - 2240
思路:spfa判断正环即可,用map把图建立出来
注意:各种数组一定要初始化…
具体代码如下
#include<iostream>
#include<map>
#include<queue>
#include<string>
#include<cstring>
using namespace std;
const int N = 50;
int n, m, cnt;
int ans[N];
double g[N][N];
double dis[N];
bool st[N];
map<string, int> S;
bool spfa(){
memset(ans, 0, sizeof ans);
memset(dis, 0, sizeof dis);
memset(st, 0, sizeof st);
dis[1] = 1000;
queue<int> q;
q.push(1);
st[1] = true;
while(q.size()){
int t = q.front();
q.pop();
st[t] = false;
for(int i=1; i<=n; ++i)
if(g[t][i] != -1 && dis[i] < dis[t]*g[t][i]){
dis[i] = dis[t] * g[t][i];
ans[i] = ans[t] + 1;
if(!st[i]){
st[i] = true;
q.push(i);
}
if(ans[i] >= n) return true;
}
}
return false;
}
int main(){
int kase = 0;
while(cin >> n, n){
cnt = 1;
S.clear();
memset(g, -1, sizeof g);
for(int i=0; i<n; ++i){
string s;
cin >> s;
S[s] = cnt++;
}
cin>>m;
for(int i=0; i<m; ++i){
string a, c; double b;
cin >> a >> b >> c;
g[S[a]][S[c]] = b;
}
if(spfa()) printf("Case %d: Yes\n", ++kase);
else printf("Case %d: No\n", ++kase);
}
return 0;
}