POJ 2240 Arbitrage

POJ 2240 Arbitrage

[★★☆☆☆]图论 最短路

  • 题目大意:

    可以简单描述为知道从i到j的汇率,问能不能赚钱

  • 样例

    输入:
    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

    输出:
    Case 1: Yes
    Case 2: No

  • 解题思路:

    水题,本来能1A的,结果交上去超时。
    看了Discuss是编译器的问题,我本来是G++换成C++就A了。
    我用的Bellman算法,Floyd也行。

  • 代码

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

struct edge {
    int from, to;
    double r;
};

edge E[1000];
int cte;

bool used[35];
string S[35];
double d[35];
int V;

int nS(string s) {
    for (int i = 1; i <= V; i++) {
        if (s == S[i]) return i;
    }
    return 0;
}

void adde(int f, int t, double r) {
    edge te = {f, t, r};
    E[cte++] = te;
}

int usedall() {
    for (int i = 1; i <= V; i++) {
        if (d[i] == 0) return i;
    }
    return 0;
}

bool bellman() {
    int u;
    for (int i = 1; i <= V; i++) d[i] = 0;
    while ((u = usedall())) {
        d[u] = 1;
        int ct;
        for (ct = 1; ct <= V; ct++) {
            bool update = false;
            for (int i = 0; i < cte; i++) {
                edge e = E[i];
                if (d[e.from] != 0 && d[e.to] < d[e.from] * e.r) {
                    d[e.to] = d[e.from] * e.r;
                    update = true;
                }
            }
            if (!update) break;
        }
        if (ct == V+1) return 1;
    }
    return 0;
}

int main() {
    int cs = 1;
    while ((cin >> V) && V != 0) {
        cte = 0;
        for (int i = 1; i <= V; i++) {
            cin >> S[i];
        }
        int n;
        string s1, s2;
        double r;
        cin >> n;
        for (int i = 1; i <= n; i++) {
            cin >> s1 >> r >> s2;
            adde(nS(s1), nS(s2), r);
        }

        cout << "Case " << cs++;
        if (bellman()) cout << ": Yes" << endl;
        else cout << ": No" << endl;

    }
    return 0;
}

你可能感兴趣的:(poj)