Bellman-Ford 扩展

#include <iostream>
using namespace std;

int n, m;
int u[100], v[100], w[100], dis[100];
const int INF = 0x3f3f3f3f;
int check = 0, flag = 0;

int main(){
    cin>>n>>m;

    for(int i=1; i<=m; i++){
        cin>>u[i]>>v[i]>>w[i];
    }

    dis[1] = 0;
    for(int i=2; i<=n; i++){
        dis[i] = INF;
    }

    //提前终止 
    for(int k=1; k<=n-1; k++){
        check = 0;
        for(int i=1; i<=m; i++){
            if(dis[v[i]] > dis[u[i]] + w[i]){
                dis[v[i]] = dis[u[i]] + w[i];
                check = 1;
            }
        }
        if(check == 0){
            break;
        }
    }

    //检测负权回路
    for(int i=1; i<=m; i++){
        if(dis[v[i]] > dis[u[i]] + w[i]){
            flag = 1;
        }
    }
    if(flag == 1){
        cout<<"存在负权回路。"<<endl;
    }else {
        for(int i=1; i<=n; i++){
            cout<<dis[i]<<' ';
        }
    }

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