Bellman-Ford

In my opinion,this way of Bellman Ford is not the solution based on dynamic programming.Because it lists all the situation,which is a waste of time,no from bottom to top,and no Memorandum.So i will give you a better solution based on dynamic programming,but tomorrow.And i just get rid of computer games,which is really a good news.Afraid of nothing and keep fighting,you are the best,i_human.

Have fun coding,i_human.Have fun coding,everyone!

THE CODE:

// Bellman-Ford 算法.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#define MAX 1000
#define N 100

using namespace std;

bool Bellman_Ford();
void prin();

struct Edge
{
	int u,v;
	int cost;
};

Edge edge[N];
int pre[N];
int ex[N];
int n,s,e;

int main()
{
	cin>>n>>s>>e;
	for(int i=1;i<=e;i++)
	{
		cin>>edge[i].u>>edge[i].v>>edge[i].cost;
	}
	for(int i=1;i<=n;i++)
		ex[i]=(i==s?0:MAX);
	pre[s]=s;
	if(Bellman_Ford())
	{
		for(int i=1;i<=n;i++)
			cout<<pre[i];
		system("pause");
		prin();
	}
	else
		cout<<"have negative circle."<<endl;
	system("pause");
	return 0;
}  

bool Bellman_Ford()
{
	for(int i=1;i<=n-1;i++)
	{
		for(int j=1;j<=e;j++)
		{
			if(ex[edge[j].v]>ex[edge[j].u]+edge[j].cost)
			{
				ex[edge[j].v]=ex[edge[j].u]+edge[j].cost;
				pre[edge[j].v]=edge[j].u;
			}
		}
	}
	bool x=1;
	for(int i=1;i<=e;i++)
		if(ex[edge[i].v]>ex[edge[i].u]+edge[i].cost)
		{
			x=0;
			break;
		}
	return x;
}

void prin()
{
	for(int i=1;i<=n;i++)
	{
		if(i==s)
			continue;
		else
		{
			int j=i;
			cout<<i<<"<--";
			while(pre[j]!=s)
			{
				cout<<pre[j]<<"<--";
				j=pre[j];
			}
			cout<<pre[j]<<endl;
		}
		system("pause");
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值