bellman-ford算法模板

#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 1005

const int inf = 0x3f3f3f3f;

using namespace std;

int n, m;
int dis[MAXN],u[MAXN],v[MAXN],w[MAXN];

void bellford(int start)
{
	for (int i = 1; i <= n; i++)
		dis[i] = inf;
	dis[start] = 0;

	for (int k = 1; k <= n - 1; k++)//外部循环n-1次
	{
		int flag = 0;
		for (int i = 1; i <= m; i++)//按边松弛
		{
			if (dis[u[i]] < inf && dis[v[i]] > dis[u[i]] + w[i])
			{
				dis[v[i]] = dis[u[i]] + w[i];
				flag = 1;
			}
		}
		if (!flag)	break;//本轮dis数组没有更新,直接退出结束算法。
	}
}

int judge()
{
	int flag = 0;
	for (int i = 1; i <= m; i++)
	{
		if (dis[v[i]] > dis[u[i]] + w[i])
			flag = 1;
		break;
	}
	if (flag)
	{
		printf("此图含有负权回路\n");
		return 0;
	}
	else 
		return 1;
}

void print()
{
	for (int i = 1; i <= n; i++)
		printf("%d ", dis[i]);
	printf("\n");
}

int main()
{
	while (scanf("%d%d", &n, &m) != EOF && (n || m))
	{
		//读入边
		for (int i = 1; i <= m; i++)
			scanf("%d%d%d", &u[i], &v[i], &w[i]);
		int start;//读入起点
		scanf("%d", &start);
		bellford(start);
		if (judge())	
			print();
	}
	return 0;
}

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