Description
Your job is to write a program that takes a list of currency exchange rates as input and then determines whether arbitrage is possible or not.
Input
Test cases are separated from each other by a blank line. Input is terminated by a value of zero (0) for n.
Output
Sample Input
3 USDollar BritishPound FrenchFranc 3 USDollar 0.5 BritishPound BritishPound 10.0 FrenchFranc FrenchFranc 0.21 USDollar 3 USDollar BritishPound FrenchFranc 6 USDollar 0.5 BritishPound USDollar 4.9 FrenchFranc BritishPound 10.0 FrenchFranc BritishPound 1.99 USDollar FrenchFranc 0.09 BritishPound FrenchFranc 0.19 USDollar 0
Sample Output
Case 1: Yes Case 2: No
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
const int maxn=1000;
map<string,int> q;
int tq;
int n,e;
struct edge
{
int s,t;
double w;
int next;
};
edge G[maxn];
int flag;
double dist[maxn];
void bellman_ford(int u)
{
memset(dist,0,sizeof(dist));
dist[u]=1;
for(int i=1;i<=n;i++)//最多走n条边 回到原点
{
for(int j=0;j<e;j++)
{
int s=G[j].s,t=G[j].t;
double w=G[j].w;
if(dist[s]*w>dist[t]) dist[t]=dist[s]*w;
}
}
if(dist[u]>1) flag=1;
}
int main()
{
int pl=1;
while(scanf("%d",&n)==1&&n)
{
q.clear();tq=0;
char str1[100],str2[100];
for(int i=0;i<n;i++)
{
scanf("%s",str1);
if(q[str1]==0) q[str1]=++tq;
}
scanf("%d",&e);
for(int i=0;i<e;i++)
{
double w;
scanf("%s%lf%s",str1,&w,str2);
G[i].s=q[str1];
G[i].t=q[str2];
G[i].w=w;
}
flag=0;
for(int i=1;i<=n;i++)
{
bellman_ford(i);
if(flag) break;
}
if(flag) printf("Case %d: Yes\n",pl++);
else printf("Case %d: No\n",pl++);
}
return 0;
}