Description
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. Then, by converting currencies, a clever trader can start with 1 US dollar and buy 0.5 * 10.0 * 0.21 = 1.05 US dollars, making a profit of 5 percent.
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.
题目就是问货币能不能通过转换而让自己增加。。。
用的SPFA来判断的环。。。枚举每一个点进行SPFA (也就是说floyd也是可以的。。。)。。。
代码如下:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue> using namespace std; const int INF=10e8;
const int MaxN=; struct Edge
{
int v;
double cost; Edge(int _v=,double _cost=):v(_v),cost(_cost) {}
}; vector <Edge> E[MaxN];
bool vis[MaxN];
int couNode[MaxN]; bool SPFA(double lowcost[],int n,int start)
{
queue <int> que;
int u,v;
double c;
int len; for(int i=;i<=n;++i)
{
vis[i]=;
couNode[i]=;
lowcost[i]=;
} vis[start]=;
couNode[start]=;
lowcost[start]=; que.push(start); while(!que.empty())
{
u=que.front();
que.pop(); vis[u]=;
len=E[u].size(); for(int i=;i<len;++i)
{
v=E[u][i].v;
c=E[u][i].cost; if(lowcost[u]*c>lowcost[v])
{
lowcost[v]=lowcost[u]*c; if(!vis[v])
{
vis[v]=;
++couNode[v];
que.push(v); if(couNode[v]>=n)
return ;
}
}
}
} return ;
} inline void addEdge(int u,int v,double c)
{
E[u].push_back(Edge(v,c));
} char ss[][];
double ans[MaxN];
int N; int find(char *s)
{
for(int i=;i<=N;++i)
if(strcmp(s,ss[i])==)
return i;
} int main()
{
int M;
bool ok;
char ts1[],ts2[];
int t1,t2;
double tr;
int cas=; for(scanf("%d",&N);N;scanf("%d",&N),++cas)
{
for(int i=;i<=N;++i)
{
scanf("%s",ss[i]); E[i].clear();
} scanf("%d",&M); for(int i=;i<=M;++i)
{
scanf("%s %lf %s",ts1,&tr,ts2);
t1=find(ts1);
t2=find(ts2); addEdge(t1,t2,tr);
} ok=; for(int i=;i<=N;++i)
if(!SPFA(ans,N,i))
{
ok=;
break;
} printf("Case %d: ",cas); if(ok)
printf("Yes\n");
else
printf("No\n"); } return ;
}