poj 2240 Arbitrage(Bellman-ford)

题意:给出n种货币,以及m种货币转换汇率。(例如USDollar 0.5 BritishPound 意思为1us=0.5br但是在题目里面0.5br不能换成1us)。问你能不能通过不停转换来赚钱。(看懂的已经发财了~)

Bellman-ford算法:通过n-1轮松弛判断有没有环。以第一种货币为起点,dis[i]代表1元第一种货币能换这么多元第i种货币。所以在松弛时越大越好。
把Bellman-ford算法模板改一下。建图时建单向边。最后判断有没有正环并且dis[1]是不是大于1。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 550;
map<string, int> ma;
int n;
int dist[MAXN];
struct Edge {
    int u, v;
    double cost;
    Edge(int _u = 0, int _v = 0, double _cost = 0): u(_u), v(_v), cost(_cost) {}
};
vector<Edge>E;
void addedg(int a, int b, double w) {
    E.push_back(Edge(a, b, w));
}
double dis[MAXN];
bool bellman_ford() {
    for(int i = 1; i <= n; i++) dis[i] = 0;

    dis[1] = 1; int len = E.size();

    for(int k = 0; k < n - 1; k++) {
        bool ok = false;

        for(int i = 0; i < len; i++) {
            int x = E[i].u; int y = E[i].v;
            double w = E[i].cost;

            if(dis[y] < dis[x]*w) {
                dis[y] = dis[x] * w;
                ok = true;
            }

        }

        if(!ok) return true;//wuhuan
    }

    for(int i = 0; i < len; i++) {
        int x = E[i].u; int y = E[i].v;

        if(dis[y] < dis[x]*E[i].cost)
            return false;
    }

    return true;
}
int main() {
//    freopen("in.txt", "r", stdin);
    ios::sync_with_stdio(false); cin.tie(0);
    int cas = 1;

    while(cin >> n) {
        E.clear();
        if(n == 0) break;

        string str;

        for(int i = 1; i <= n; i++) {
            cin >> str;
            ma[str] = i;
        }

        int m; cin >> m;
        string a, b; double w;

        for(int i = 1; i <= m; i++) {
            cin >> a >> w >> b;
            addedg(ma[a], ma[b], w);
//            addedg(ma[b], ma[a], w);
        }

        if(!bellman_ford() || dis[1] > 1)
            cout << "Case " << cas++ << ": Yes";
        else cout << "Case " << cas++ << ": No";

        cout << endl;
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值