Poj 3259 Wormholes

本文讨论了使用Bellman算法解决具有时间扭曲虫洞的路径优化问题,通过实施循环迭代来寻找最短路径,并在特定条件下检测到可能的时间减少回路。

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

Bellman算法。进行n-1次循环之后如果还能继续修改使dis减小,说明存在可以使时间变小的回路。

/*
Poj: 3259: Wormholes
*/
#include <iostream>
#include <cstdio>
#include <cstring>

#define Max 32767

using namespace std;

const int M = 2705;
const int N = 505;

struct Path {
    int a, b;
    int t;
}edges[M*2];

int dis[N];
int f;
int n, m, w;
int total;

bool bellman();

int main()
{
    //freopen("data.in", "rb", stdin);
    cin >> f;
    while(f--) {
        cin >> n >> m >> w;
        total = 0;
        for(int i = 0; i < m; i++) {
            cin >> edges[total].a >> edges[total].b >> edges[total].t;
            total++;
            edges[total].a = edges[total-1].b;
            edges[total].b = edges[total-1].a;
            edges[total].t = edges[total-1].t;
            total++;
        }
        for(int i = 0; i < w; i++) {
            cin >> edges[total].a >> edges[total].b >> edges[total].t;
            edges[total].t = 0 - edges[total].t;
            total++;
        }
        
        for(int i = 2; i < n + 1; i++) {
            dis[i] = Max;
        }
        dis[1] = 0;
        
        if(bellman()) {
            cout << "YES" << endl;
        }
        else {
            cout << "NO" << endl;
        }
    }
    
    return 0;
}

bool bellman()
{
    for(int i = 0; i < n - 1; i++) {
        bool flag = true;
        for(int j = 0; j < total; j++) {
            int v1 = edges[j].a;
            int v2 = edges[j].b;
            if(dis[v1] != Max && dis[v1] + edges[j].t < dis[v2]) {
                dis[v2] = dis[v1] + edges[j].t;
                flag = false;
            }
        }
        if(flag)
            break;
    }
    
    for(int i = 0; i < total; i++) {
        int v1 = edges[i].a;
        int v2 = edges[i].b;
        if(dis[v1] != Max && dis[v1] + edges[i].t < dis[v2])
            return true;
    }    
    return false;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值