Bellman-Ford(贝尔曼,福特)算法——解决负权边

Dijkstra算法不能解决带有负权边的图(边的权值为负数)。而Bellman-Ford算法可以解决这个问题

这个算法是Bellan和Ford各自独立发明的

#include<iostream>
using namespace std;
int main() {
	int dis[10], bak[10];//bac用来备份dis
	int n, m, u[10], v[10], w[10], check, flag;
	int inf = 99999999;//无穷大
	cout << " 输入顶点个数和边的条数" << endl;
	cin >> n >> m;
	for (int i = 1; i <= m; i++)//读入边
		cin >> u[i] >> v[i] >> w[i];//从u到v的边权是w
	for (int i = 1; i <= n; i++)
		dis[i] = inf;//初始化数组
	dis[1] = 0;
	for (int k = 1; k <= n - 1; k++) {//bellman算法
		for (int i = 1; i <= n; i++)
			bak[i] = dis[i];//备份数组
		for (int i = 1; i <= m; i++) {//进行一轮松弛
			if (dis[v[i]] > dis[u[i]] + w[i])
				dis[v[i]] = dis[u[i]] + w[i];
			check = 0;//检测dis是否需要更新
		}
		for (int i = 1; i <= n; i++) {
			if (bak[i] != dis[i]) {
				check = 1;
				break;
			}
		}
		if (check == 0)//如果没有更新提前结束算法
			break;
		}
	//检测负权回路
	flag = 0;
	for (int i = 1; i <= n; i++)
		if (dis[v[i]] > dis[u[i]] + w[i])
			flag = 1;
	if (flag == 1)
		cout << "含有负权回路" << endl;
	else{
		for (int i = 1; i <= n; i++)
			cout << dis[i] << " ";
	}
	return 0;
}

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