POJ-2240 Arbitrage bellman

本文介绍了一种使用Bellman-Ford算法来检测图中是否存在负权重环的方法,并通过一个具体的编程实现示例来说明这一过程。该示例基于POJ-1860问题进行改进,展示了如何通过增加外循环次数来判断是否有负环存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

跟POJ-1860基本一样,bellman求是否存在环。这里吸取了别人的代码,让bellman算法的外循环直接增加一次,再判定是否在这个过程中有无更新推出的情况。

代码如下:

#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <map>
#include <string>
using namespace std;

int N, pos, cnt;
double dis[35];
map<string,int>mp;

struct Node
{
    int x, y;
    double rate;
}e[905];

bool bellman()
{
    int flag;
    fill(dis, dis+35, 1000);
    for (int i = 1; i <= N; ++i) {
        flag = 0;
        for (int j = 1; j <= pos; ++j) {
            if (dis[ e[j].x ] * e[j].rate - dis[ e[j].y ] > 1e-6) {
                dis[ e[j].y ] = dis[ e[j].x ] * e[j].rate;
                flag = 1;
            }
        }
        if (!flag) {
            break;
        }
    }
    if (flag) {
        return true;
    }
    else {
        return false;
    }
}

int main()
{
    int M, ca = 0;
    char a[105], b[105];
    double rate;
    while (scanf("%d", &N), N) {
        mp.clear();
        pos = cnt = 0;
        for (int i = 1; i <= N; ++i) {
            scanf("%s", a);
            mp[a] = ++cnt;
        }
        scanf("%d", &M);
        for (int i = 1; i <= M; ++i) {
            scanf("%s %lf %s", a, &rate, b);
            ++pos;
            e[pos].x = mp[a], e[pos].y = mp[b];
            e[pos].rate = rate;
        }
        printf("Case %d: ", ++ca);
        printf(bellman() ? "Yes\n" : "No\n");
    }
    return 0;
}

转载于:https://www.cnblogs.com/Lyush/archive/2012/07/01/2571993.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值