<span style="font-size:14px;">//Bellman-Ford_001.cpp -- 单源最短路
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
typedef long long ll;
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxE = 1000 + 10;
const int maxV = 100 + 10;
struct edge{
int from, to, cost;
};
edge es[maxE];
int d[maxV];
int V, E;
void Bellman_Ford(int s)
{
fill(d, d+V, INF);
d[s] = 0;
for( int i=0; i<V-1; i++ )
{
bool update = false;
for( int j=0; j<E; i++ )
{
edge e = es[j];
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;
}
bool flag = 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 )
{
flag = true;
break;
}
}
if( flag )
cout<<"存在负圈。"<<endl;
}
int main()
{
while( cin>>V>>E && V )
{
int a, b, c;
for( int i=0; i<E; i++ )
{
cin>>a>>b>>c;
es[i] = (edge){a, b, c};
}
Bellman_Ford(0);
}
return 0;
}</span>Bellman-Ford算法
最新推荐文章于 2025-12-30 15:52:40 发布
本文介绍了使用Bellman-Ford算法解决单源最短路径问题的方法,包括算法原理、代码实现及应用实例。通过实例演示了如何在给定边集和顶点数的情况下,计算从指定起点到所有其他顶点的最短路径。
2万+

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



