UVa436 - Arbitrage (II)

#include <cstdio>
#include <map>
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <algorithm>

using namespace std;

const int N = 35;
const double EPS = 1e-6;

#define REP(i, a, b) for (int i = a; i < b; i++)
#define rep(i, b) REP(i, 0, b)

double f[N][N];
map<string, int> strMap;
int n;

int idx(string &s);
bool floyd_warshall(int n);

int main()
{
    string s;
    int m;
    string s1, s2;
    double rate;
    int t = 1;

#ifndef ONLINE_JUDGE
    //freopen("d:\\OJ\\uva_in.txt", "r", stdin);
    ifstream cin("uva_in.txt");
#endif
    
    while (cin >> n, n) {
        strMap.clear();
        rep(i, n) {
            cin >> s;
            idx(s);
        }
        cin >> m;

        rep(i, n) {
            rep(j, n) {
                if (i == j) f[i][j] = 1;
                else f[i][j] = -1;
            }
        }

        rep(i, m) {
            cin >> s1 >> rate >> s2;  
            int n1 = strMap[s1], n2 = strMap[s2];
            f[n1][n2] = rate;
        }

        cout << "Case " << t++ << ": ";
        cout << (floyd_warshall(n) ? "Yes": "No") << endl;
    }
    return 0;
}

int idx(string &s)
{
    if (strMap.count(s)) return strMap[s];

    int ret = strMap.size();

    strMap[s] = ret;

    return ret;
}

bool floyd_warshall(int n)
{
    rep(k, n) {
        rep (i, n) {
            rep(j, n) {
                if (f[i][k] > 0 && f[k][j] > 0) {
                    f[i][j] = max(f[i][j], f[i][k] * f[k][j]);
                }
            }
        }
    }
    
    rep(i, n) {
        if (f[i][i] > 1) return true;
    }

    return false;
}

你可能感兴趣的:(UVa436 - Arbitrage (II))