# Bellman-ford最短路算法

## Bellman-ford 模板

d[i] = min{q[j]+(从j到i的边权)|e∈E(i,j)}

4 4
1 2 1
2 3 3
1 4 2
4 3 4

``````//
// Created by luozujian on 17-10-13.
//
//最短路算法
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#define INF 0x3f3f3f3f
using namespace std;
const int maxv = 1e2+5;
const int maxe = 1e2+5;
struct edge{
int from,to,cost;
};
edge es[maxe];
int d[maxv];
int e,v;
void Bellman_ford(int s)
{
for(int i=1;i<=v;i++) d[i] = INF;
d[s] = 0;
while(true)
{
bool update = false;
for(int i=0;i<e;i++)
{
edge e = es[i];
if(d[e.from]!=INF && d[e.to] > d[e.from] + e.cost)
{
d[e.to] = d[e.from] + e.cost;
update = true;
}
}
if(!update) break;
}
}
void solve()
{

Bellman_ford(1);
printf("%d\n",d[4]);
}
int main()
{
scanf("%d%d",&v,&e);
for(int i=0;i<e;i++)
{
int s,t,cost;
scanf("%d%d%d",&s,&t,&cost);
es[i].from = s;
es[i].to = t;
es[i].cost = cost;
}
solve();
return 0;
}
/* 4 4 1 2 1 2 3 3 1 4 2 4 3 4 */``````
原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/qq_37129433/article/details/78230450
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。