首页 > 其他 > 详细

贝尔曼福特算法

时间:2014-03-21 19:46:14      阅读:519      评论:0      收藏:0      [点我收藏+]
//Bellman_ford
#include<iostream>
using namespace std;
struct Edge{
	int v,e,weight;
}a[1000];
int dist[1000];
int node,edge,source,i,j;
bool Bellman_ford()
{
    for(i=2;i<=node;i++)
	{
		for(j=1;j<=edge;j++)
		{
			if(dist[a[j].e]>dist[a[j].v]+a[j].weight)
			   dist[a[j].e]=dist[a[j].v]+a[j].weight;
		}
	}
	for(j=1;j<=edge;j++)
	{
		if(dist[a[j].e]>dist[a[j].v]+a[j].weight)
		return false;
	}	
	return true;
}
int main()
{
	cin>>node>>edge>>source;
	for(i=1;i<=edge;i++)
	dist[i]=9999;
	for(i=1;i<=edge;i++)
	{
	    cin>>a[i].v>>a[i].e>>a[i].weight;
	    if(source==a[i].v)
	    {
	    	dist[source]=0;
	    	dist[a[i].e]=a[i].weight;
	    }
	}
	if(Bellman_ford())
	{
		for(i=1;i<=edge;i++)
		cout<<dist[i]<<endl;
	}
	return 0;
}
/*
input :
5 5 1
1 2 10
2 3 50
3 5 10
1 5 100
1 4 30
output:
0
10
60
30
70
*/
/*
author Sunshine_小高 
*/

贝尔曼福特算法,布布扣,bubuko.com

贝尔曼福特算法

原文:http://blog.csdn.net/guanjungao/article/details/21738925

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!