bellman 算法单源最短路径算法(可负边)

#include<bits/stdc++.h>
using namespace std;
struct Node {
    int from,to,w
}V[MAX_edge];
int n,m,d[MAX];//点和边的数量
bool bellman(int s){//求s到各点的最短距离
    for(int i=1;i<=n;i++)d[i]=inf;
    d[s]=0;
    for(int i=1;i<n;i++)//最多进行n-1次操作
        for(int j=1;j<=m;j++){//遍历每条边进行松弛
            int from=v[j].from,to=v[j].to,w=v[j].w;
            if(dis[to]>dis[from]+w)//如果可以松弛
                dis[to]=dis[from]+w;
        }//求到了单源最短路径
    for(int i=1;i<=m;i++)
        if(dis[v[i]].to>dis[v[i].from]+v[i].w)//如果存在负环
                return false;
    return true ;
}

猜你喜欢

转载自blog.csdn.net/xizi_ghq/article/details/88371059