参考程序:
http://www.java3z.com/cwbwebhome/article/article1/1359.html?id=4720
#include<limits>
#include<iostream>
#include<iomanip>
#include<stack>
using namespace std;
const int NUM = 6;
void BellmanFord(int sourceVer, float cost[][NUM+1], float dis[], int path[]);
float cost[NUM+1][NUM+1] =
{ {0,0,0,0,0,0,0},
{0,0,2,4,INT_MAX,INT_MAX,INT_MAX},
{0,INT_MAX,0,-3,1,5,INT_MAX},
{0,INT_MAX,INT_MAX,0,-4,-2,INT_MAX},
{0,INT_MAX,INT_MAX,INT_MAX,0,INT_MAX,8},
{0,INT_MAX,INT_MAX,INT_MAX,4,0,6},
{0,INT_MAX,INT_MAX,INT_MAX,INT_MAX,INT_MAX}};
int _tmain(int argc, _TCHAR* argv[])
{
int source = 1;
float dis[NUM+1];
int path[NUM+1];
BellmanFord( source, cost, dis, path);
for(int vertex = 1; vertex<=NUM; vertex++)
{
if( vertex != source )
{
stack<int> pathStack;
cout <<"The distance from" << setw(5) << source << " to" << setw(5) << vertex << " is" << setw(5) << dis[vertex] << ", " << "The path is:" << endl;
pathStack.push(vertex);
int nextVer = path[vertex];
do
{
nextVer = path[nextVer];
pathStack.push(nextVer);
}while(nextVer != source);
while( !pathStack.empty() )
{
cout << pathStack.top() << setw(5);
pathStack.pop();
}
cout << endl;
}
}
return 0;
}
void BellmanFord(int sourceVer, float cost[][NUM+1], float dis[], int path[])
{
for(int i = 1; i <= NUM; i++)
{
dis[i] = cost[sourceVer][i];
if( cost[sourceVer][i] != INT_MAX )
path[i] = sourceVer;
else
path[i] = -1;
}
for(int pathEdgeNum = 2; pathEdgeNum <= NUM-1; pathEdgeNum++)
{
for(int vertexNum = 1; vertexNum <= NUM; vertexNum++)
{
if( vertexNum!=sourceVer )
{
for(int midVertexNum = 1; midVertexNum <= NUM; midVertexNum++)
{
if( cost[midVertexNum][vertexNum] != INT_MAX && dis[midVertexNum] != INT_MAX)
{
int tmpDis = dis[midVertexNum] + cost[midVertexNum][vertexNum];
if( dis[vertexNum] > tmpDis)
{
dis[vertexNum] = tmpDis;
path[vertexNum] = midVertexNum;
}
}
}
}
}
}
}