POJ-3259 Wormholes (bellman_ford算法)

题目大意:

大概就是说,一个农夫在自己的农庄里面有n块田地。 在这n块田地中有m条路径(双向),以及w条虫洞,虫洞可以使得回到n时刻前的某块地上。
问,农夫能否在这个农庄里面通过虫洞看到从前的自己。

算法分析:

这道题就是判断是否会出现负环,直接把虫洞当成一条权值为负值的路径即可。
用到的算法是ballman_ford算法。直接是裸的算法模板。我因为个人问题WA了n次,最后写了n次后才发现问题所在。 bellman_ford算法网上有很多,这里就不赘述了(其实只是不懂原理好吗= =)

代码:

#include <iostream>
#include <algorithm>
#include <stdio.h>

#define MAXNUM 0x7ffffff

using namespace std;

struct node
{
    int begin;
    int end;
    int cost;
} edge[6000];

int n, m, w, count_;
int maxn[550];

bool bellman_ford()
{
    bool flag;
    int x, y, cost;

    for (int i = 1; i <= n; i++) {
        maxn[i] = MAXNUM;
    }
    maxn[1] = 1;
    for (int i = 1; i <= n; i++) {
        flag = true;
        for (int j = 1; j <= count_; j++) {
            x = edge[j].begin;
            y = edge[j].end;
            cost = edge[j].cost;
            if (maxn[x] + cost < maxn[y]) {
                maxn[y] = maxn[x] + cost;
                flag = false;
            }
        }
        if (flag)
            break;
    }
    for (int i = 1; i <= count_; i++) {
        x = edge[i].begin;
        y = edge[i].end;
        cost = edge[i].cost;
        if (maxn[y] > maxn[x] + cost)
            return true;
    }
    return false;
}

int main()
{
    int t;
    int x, y, cost;

    scanf("%d", &t);
    while (t--) {
        count_ = 0;
        scanf("%d%d%d", &n, &m, &w);
        for (int i = 1; i <= m; i++) {
            scanf("%d%d%d", &x, &y, &cost);
            edge[++count_].begin = x;
            edge[count_].end = y;
            edge[count_].cost = cost;
            edge[++count_].begin = y;
            edge[count_].end = x;
            edge[count_].cost = cost;
        }
        for (int i = 1; i <= w; i++) {
            scanf("%d%d%d", &x, &y, &cost);
            edge[++count_].begin = x;
            edge[count_].end = y;
            edge[count_].cost = -cost;
        }
//        for (int i = 1; i <= count_; i++) {
//            printf("begin:%d\tend:%d\tcost:%d\n", edge[i].begin, edge[i].end, edge[i].cost);
//        }
        if (bellman_ford()) {
            printf("YES\n");
        } else {
            printf("NO\n");
        }
    }

    return 0;
}

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/qq_32685139/article/details/52862120
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞