POJ 3259 Bellman-Ford算法

感觉看到与路径有关,有负权值,输出为YES or NO的基本都是Bellman-Ford算法

这个题注意一点就行,普通路径是双向的,虫洞是单向的。

//224K 250MS
#include <iostream>
#include <vector>
#include <sstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <memory.h>
#include <math.h>
#include <fstream>
#include <map>
#include <algorithm>
using namespace std;
int f;
int n, m, w;
int dist[1005];
int all = 0;
struct edge {
    int from;
    int to;
    int dist;
}e[5205];

bool bellford(){
    bool flag = false;//如果flag在for循环中没有更新,说明已经没有需要更新的路径了
    for (int i = 1; i <= n - 1; i++) {
        for (int j = 0; j < all; j++) {
            if (dist[e[j].to] > dist[e[j].from] + e[j].dist) {//松弛是Bellman-Ford的核心
                dist[e[j].to] = dist[e[j].from] + e[j].dist;
                flag = true;
            }
        }
        if (!flag) {
            break;
        }
    }
    for (int i = 0; i < all; i++) {
        if (dist[e[i].to] > dist[e[i].from] + e[i].dist) {
            return true;
        }
    }
    return false;
}

int main(){
    cin >> f;

    int a, b, c;
    for (int index = 0; index < f; index++) {
        cin >> n >> m >> w;
        all = 0;
        memset(dist, 10001, sizeof(dist));
        for (int i = 0; i < m; i++) {
            cin >> a >> b >> c;
            e[all].from = a;
            e[all].to = b;
            e[all++].dist = c;
            e[all].from = b;
            e[all].to = a;
            e[all++].dist = c;
        }
        for (int i = 0; i < w; i++) {
            cin >> a >> b >> c;
            e[all].from = a;
            e[all].to = b;
            e[all++].dist = -c;
        }
        if (bellford()) {
            cout << "YES" << endl;
        }else{
            cout << "NO" << endl;
        }
    }



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