Bellman-Ford算法

本文介绍了使用Bellman-Ford算法解决单源最短路径问题的方法,包括算法原理、代码实现及应用实例。通过实例演示了如何在给定边集和顶点数的情况下,计算从指定起点到所有其他顶点的最短路径。
<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>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值