// Bellman_Ford.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stack>
#define MAX_VALUE 1000
using namespace std;
struct Edge{
int Begin;
int End;
int Weight;
int Pre;
};
struct MGraph
{
Edge edges[MAX_VALUE];
int iVertexCount, iEdageCount;
};
void ReadDate(MGraph *mGraph, int *iBegin, int *iEnd);
bool Bellman_Ford(MGraph *mGraph, int *pArrDis, int *pArrPath, int iBegin);
void PrintResult(int *pArrDis, int *pArrPath, int iBegin, int iEnd);
int main()
{
int iBegin, iEnd;
int *pArrPath = new int[MAX_VALUE];
int *pArrDis = new int[MAX_VALUE];
MGraph mGraph;
ReadDate(&mGraph, &iBegin, &iEnd);
Bellman_Ford(&mGraph, pArrDis, pArrPath, iBegin);
PrintResult(pArrDis, pArrPath, iBegin, iEnd);
system("pause");
return 0;
}
void ReadDate(MGraph *mGraph, int *iBegin, int *iEnd){
//cout << "请输入顶点数量" << endl;
//cin >> mGraph->iVertexCount;
//cout << "请输入邻接矩阵数据:" << endl;
//for (int iRow = 1; iRow <= mGraph->iVertexCount; iRow++){
// for (int iCol = 1; iCol <= mGraph->iVertexCount; iCol++){
// cin >> mGraph->edges[iRow][iCol];
// }
//}
cout << "请输入顶点数和边数" << endl;
cin >> mGraph->iVertexCount >> mGraph->iEdageCount;
cout << "请输入连通边及权重" << endl;
for (int i = 1; i <= mGraph->iEdageCount; i++){
cin >> mGraph->edges[i].Begin >> mGraph->edges[i].End >> mGraph->edges[i].Weight;
}
cout << "请输入查询的起点和终点" << endl;
cin >> *iBegin >> *iEnd;
}
bool Bellman_Ford(MGraph *mGraph, int *pArrDis, int *pArrPath, int iBegin){
for (int i = 0; i <= mGraph->iVertexCount; i++){
pArrDis[i] = MAX_VALUE;
}
for (int i = 0; i <= mGraph->iVertexCount; i++){
pArrPath[i] = -1;
}
pArrDis[iBegin] = 0;
for (int i = 1; i <= mGraph->iVertexCount; i++){
bool flag = true;
for (int j = 1; j <= mGraph->iEdageCount; j++){
if (pArrDis[mGraph->edges[j].End] > pArrDis[mGraph->edges[j].Begin] + mGraph->edges[j].Weight){
pArrDis[mGraph->edges[j].End] = pArrDis[mGraph->edges[j].Begin] + mGraph->edges[j].Weight;
pArrPath[mGraph->edges[j].End] = mGraph->edges[j].Begin;
flag = false;
}
}
if (flag){
break;
}
if (i == mGraph->iVertexCount){
return false;
}
}
return true;
}
void PrintResult(int *pArrDis, int *pArrPath, int iBegin, int iEnd){
cout << "从" << iBegin << "开始到" << iEnd << "的最短路径长度为";
cout << pArrDis[iEnd] << endl;
cout << "所经过的最短路径节点为:";
stack<int> stackVertices;
int k = iEnd;
do{
stackVertices.push(k);
k = pArrPath[k];
} while (k != pArrPath[k] && k != -1);
cout << stackVertices.top();
stackVertices.pop();
unsigned int nLength = stackVertices.size();
for (unsigned int nIndex = 0; nIndex < nLength; nIndex++)
{
cout << " -> " << stackVertices.top();
stackVertices.pop();
}
cout << endl;
}