题意:有n种货币以及m种两个货币之间的兑换比率,求有没有一种盈利方式,即从一种货币出发,在经过一系列兑换后在兑换回来,其值会增大。
分析:刚开始想的是BFS从一个点出发的所有路径,但感觉这样实在不太好,后来才知道只要用Floyd求两点之间的最长路径,对原来Floyd的代码稍作改动就行了。
代码如下:
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <list>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define lrt rt << 1
#define rrt rt << 1|1
#define root 1,m,1
#define BitCount(x) __builtin_popcount(x)
#define BitCountll(x) __builtin_popcountll(x)
#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
const double PI = acos(-1.0);
const int INF=1e9;
using namespace std;
const double eps = 1e-5;
const int MAXN = 300 + 10;
const int MOD = 1000007;
const double M=1e-8;
const int N=1100;
typedef pair<int, int> pii;
typedef pair<int, string> pis;
int n,m,cnt;
double g[N][N],d[N][N];
map<string,int> hs;
void floyd()
{
int i,j,k;
for (i=0;i<n;i++)
for (j=0;j<n;j++)
{
if (g[i][j]>0)
d[i][j]=g[i][j];
else
d[i][j]=0;
}
for (k=0;k<n;k++)
for (i=0;i<n;i++)
for (j=0;j<n;j++) if ( d[i][j]<d[i][k]*d[k][j])
{
d[i][j]=d[i][k]*d[k][j];
}
}
int main()
{
int i,j,k=1;
while(~scanf("%d",&n),n)
{
string s,ss;
MS(g,0);
hs.clear();
for (i=j=0;i<n;i++) {
cin>>s;
if (!hs[s]) hs[s]=j++;
}
scanf("%d",&m);
for (i=0;i<m;i++) {
double a;
cin>>s>>a>>ss;
g[hs[s]][hs[ss]]=a;
}
floyd();
for (i=0;i<n;i++)
if (d[i][i]>1) {
printf("Case %d: Yes\n",k++);
break;
}
if (i==n) printf("Case %d: No\n",k++);
}
}