699: Arbitrage
解法:
初始化二维汇率图
经过 Floyd-Warshall 算法后,二维数组会被更新为所有货币对之间的最大汇率路径。如果存在 g[i][i] > 1
,则表示存在套汇。
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
const int N = 1e3;
double g[N][N];
int main() {
int n, m, cnt = 1;
while (cin >> n, n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
g[i][j] = 0;
}
}
string s1, s2;
map<string, int> mp;
for (int i = 0; i < n; i++) {
cin >> s1;
mp[s1] = i;
}
cin >> m;
for (int i = 0; i < m; i++) {
double x;
cin >> s1 >> x >> s2;
g[mp[s1]][mp[s2]] = x;
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
g[i][j] = max(g[i][j], g[i][k] * g[k][j]);
}
}
}
int flag = 0;
for (int i = 0; i < n; i++) {
if (g[i][i] > 1) {
flag = 1;
break;
}
}
cout << "Case " << cnt << " " << (flag ? "Yes" : "No") << endl;
cnt++;
}
return 0;
}