Bellman-Ford_检测负权回路 ---- 啊哈算法

//
// Created by jal on 18-9-3.
//
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 50, MAXM = 10000, MAX = 99999;
int u[MAXM], v[MAXM], w[MAXM], dis[MAXN];
int n, m;

void init() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        dis[i] = MAX;
    }
    dis[1] = 0;
    for (int i = 1; i <= m; i++) {
        cin >> u[i] >> v[i] >> w[i];
    }
}

int main() {
    init();

    //Bellman算法核心语句 4句
    for (int k = 1; k < n; k++) {
        for (int i = 1; i <= m; i++) {
            if (dis[v[i]] > dis[u[i]] + w[i]) {
                dis[v[i]] = dis[u[i]] + w[i];
            }
        }
    }
    int flag = 0;
    for(int i = 1; i <= m; i++){
        if (dis[v[i]] > dis[u[i]] + w[i]) {
            flag = 1;
        }
    }

    if(flag){
        cout << "此图含有负权回路!" << endl;
    } else{
        cout << "此图不含负权回路!" << endl;
        for(int i = 1; i <= n; i++){
            cout << dis[i] << " ";
        }
        cout << endl;
    }
}



/* input: 6 9 1 2 1 1 3 12 2 3 9 2 4 3 3 5 5 4 3 4 4 5 13 4 6 15 5 6 4 output: 此图不含负权回路! 0 1 8 4 13 17 input: 5 5 2 3 2 1 2 -3 1 5 5 4 5 2 3 4 3 output: 此图不含负权回路! 0 -3 -1 2 4 */
    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/jal517486222/article/details/82347584
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞