题意:
给你一些外汇,以及外汇A可以换多少外汇B,现在问你能否存在一种相互转换的方式最终可以通过这种方式赚钱
思路:
判断正环
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <queue>
#include <map>
#include <algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = 30+5;
using namespace std;
int n,m;
double G[maxn][maxn];
map<string , int> mp;
int Id(string s){
if(mp.count(s) == 0) mp.insert(make_pair(s, mp.size()));
return mp[s]+1;
}
double d[maxn];
bool inq[maxn];
int cnt[maxn];
bool BellmanFord(int s){
memset(inq, 0, sizeof(inq)); inq[s] = 1;
memset(d, 0, sizeof(d)); d[s] = 1;
memset(cnt, 0, sizeof(cnt)); cnt[s] = 1;
queue<int> Q;
Q.push(s);
while(!Q.empty()){
int x = Q.front(); Q.pop();
inq[x] = 0;
for(int i = 1; i <= n; ++i){
if(d[i] < d[x]*G[x][i]){
d[i] = d[x]*G[x][i];
if(!inq[i]){ Q.push(i); inq[i] = 1; if(++cnt[i] > n) return 1;}
}
}
}
return 0;
}
int main()
{
//freopen("in.txt","r",stdin);
int kase = 1;
while(cin>>n&&n){
memset(G, 0, sizeof(G));
mp.clear();
string s1,s2;
double rate;
for(int i = 0; i < n; ++i){ cin>>s1; Id(s1);}
cin>>m;
for(int i = 0; i < m; ++i){
cin>>s1>>rate>>s2;
//printf("%d--%d\n",Id(s1),Id(s2));
G[Id(s1)][Id(s2)] = rate;
}
printf("Case %d: ", kase++);
if(BellmanFord(1)) printf("Yes\n");
else printf("No\n");
}
fclose(stdin);
return 0;
}