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");
}
}