Arbitrage
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. Input
The input will contain one or more test cases. Om the first line of each test case there is an integer n (1<=n<=30), representing the number of different currencies. The next n lines each contain the name of one currency. Within a name no spaces will appear. The next line contains one integer m, representing the length of the table to follow. The last m lines each contain the name ci of a source currency, a real number rij which represents the exchange rate from ci to cj and a name cj of the destination currency. Exchanges which do not appear in the table are impossible.
Test cases are separated from each other by a blank line. Input is terminated by a value of zero (0) for n. Output
For each test case, print one line telling whether arbitrage is possible or not in the format "Case case: Yes" respectively "Case case: No".
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 Source |
提示
题意:
给你能兑换的货币种类,看看能不能套汇。例如:1美元=0.5英磅,1英镑=10法郎,1法郎=0.21美元,那么我们可以这样做1美元=0.5*10*0.21→1.05美元。
思路;
简单floyd。
示例程序
Source Code
Problem: 2240 Code Length: 1368B
Memory: 376K Time: 32MS
Language: GCC Result: Accepted
#include <stdio.h>
#include <string.h>
double map[30][30];
int flody(int n)
{
int i,i1,i2;
for(i=0;n>i;i++)
{
for(i1=0;n>i1;i1++)
{
for(i2=0;n>i2;i2++)
{
if(map[i1][i2]<map[i1][i]*map[i][i2]) //这里当做求最长路径,加法换乘法
{
map[i1][i2]=map[i1][i]*map[i][i2];
}
}
}
}
for(i=0;n>i;i++)
{
if(map[i][i]>1) //每种货币只要有一种能套汇即可
{
return 1;
}
}
return 0;
}
int main()
{
char money[30][30],x[30],y[30];
int i,i1,i2,n,m,a,b;
double rate;
scanf("%d",&n);
for(i=1;n!=0;i++)
{
memset(map,0,sizeof(map));
for(i1=0;n>i1;i1++)
{
scanf("%s",money[i1]);
}
scanf("%d",&m);
for(i1=1;m>=i1;i1++)
{
scanf("%s %lf %s",x,&rate,y);
for(i2=0;n>i2;i2++)
{
if(strcmp(money[i2],x)==0)
{
a=i2;
}
if(strcmp(money[i2],y)==0) //这里注意不要用else if,题目会有自己兑换自己的数据,即x=y
{
b=i2;
}
}
map[a][b]=rate;
}
if(flody(n)==1)
{
printf("Case %d: Yes\n",i);
}
else
{
printf("Case %d: No\n",i);
}
scanf("%d",&n);
}
return 0;
}