Bellman_ford 求最短路模板

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <queue>
#define CLR(a,b) memset(a,(b),sizeof a)

using namespace std;

const int INF = 0x3f3f3f3f;
const int maxx = 1e5;
struct edge{
    int from,to,cost;
}es[maxx];
int dis[maxx];
int n,m;
void Bellman(int s){
    CLR(dis, INF);
    dis[s] = 0;
    while(true){
        bool update = false;
        for(int i = 0 ; i < m ;i++){
            edge e = es[i];
            if(dis[e.from]!=INF&&dis[e.to] > dis[e.from] + e.cost){
                dis[e.to] = dis[e.from]+e.cost;
                update = true;
            }
        }
        if(!update)
            break;

    }
}


int main(){

    scanf("%d %d",&n,&m);
    for(int i = 0 ;i < m ;i++){
        scanf("%d %d %d",&es[i].from,&es[i].to,&es[i].cost);
    }
    Bellman(1);
    printf("%d\n",dis[5]);
    return 0;
}

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