Arbitrage is the use of discrepancies in currency exchange rates to transform one unit of a currency into more than one unit of the same currency. For example, suppose that 1 US Dollar buys 0.5 British pound, 1 British pound buys 10.0 French francs, and 1 French franc buys 0.21 US dollar.
用map將字符串當做點,Bellman-Ford求正權迴路……
#include<iostream>
#include<queue>
#include<math.h>
#include<stdio.h>
#include<string>
#include<map>
using namespace std;
#define N 1000+5
#define LL long long int
#define pow(a) ((a)*(a))
#define INF 0x3f3f3f3f
#define mem(arr,a) memset(arr,a,sizeof(arr))
map<string, int>maps;
struct edge{
int from;
int to;
double rate;
};
edge es[N];
int V, E;
double d[N];
int counts = 1;
int bellman(int s){
mem(d, 0);
d[s] = 1;
int cnt = 0;
while (1){
cnt++;
bool update = false;;
for (int i = 0; i < E; i++){
if (d[es[i].to]<d[es[i].from] * es[i].rate){
d[es[i].to] = d[es[i].from] * es[i].rate;
update = true;
}
}
if (!update)return false;
if (cnt == V)return true;
}
return false;
}
int main(){
while (cin >> V)
{
if (V == 0)break;
for (int i = 1; i <= V; i++){
string s; cin >> s;
maps[s] = i;
}
cin >> E;
for (int i = 0; i < E; i++){
string a, b;
double rate;
cin >> a;
cin >> rate;
cin >> b;
es[i].rate = rate;
es[i].from = maps[a];
es[i].to = maps[b];
}
printf("Case %d: ", counts++);
if (bellman(1))cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}