#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 求最短路模板
最新推荐文章于 2024-05-02 21:39:56 发布
本文介绍了一种使用Bellman-Ford算法解决单源最短路径问题的C++实现方法。通过具体的代码示例,展示了如何初始化图结构、进行松弛操作以更新节点距离,并最终输出从指定起点到目标节点的最短路径长度。
428

被折叠的 条评论
为什么被折叠?



