题目内容:
有5个城市(A,B,C,D,E),其中每个城市到其他城市的直达距离已知,两个城市之间只有一条公路。计算从城市A到其他任意城市的最短路径距离。
输入描述
4行数据, 第一行是A到(B,C,D,E)的直达距离,第二行是B到(C,D,E)的直达距离,。。。,第4行是D到E的直达距离。
输出描述
A城市到(B,C,D,E)的最短距离。
输入样例
2 3 4 5 3 4 2 4 3 3
输出样例
2 3 4 4
#include <iostream>
using namespace std;
#define INFINITE 0x7fffffff
int PathDijkstra(int cost[5][5], int n, int s, double Dist[], int Pre[]){
int i, j, k, count;
int BoolInA[100];
double mindis;
int minpnt;
for(i = 0; i < n; i++){
Dist[i] = cost[s][i];
Pre[i] = s;
BoolInA[i] = 0;
}
BoolInA[s] = 1;
for(count = 1; count <= n - 1; count++){
mindis = INFINITE;
for(i = 0; i < n; i++){
if(!BoolInA[i] && mindis > Dist[i]){
mindis = Dist[i];
minpnt = i;
}
}
BoolInA[minpnt] = 1;
for(i = 0; i < n; i++){
if(!BoolInA[i] && Dist[i] > Dist[minpnt] + cost[minpnt][i]){
Dist[i] = Dist[minpnt] + cost[minpnt][i];
Pre[i] = minpnt;
}
}
}
return 1;
}
int main(){
int n = 5;
int cost[5][5], i, j, k;
double dist[100];
int pre[100];
for(i = 0; i < n; i++){
for(j = 1; j < n; j++){
if(i < j){
cin >> cost[i][j];
}else{
cost[i][j] = INFINITE;
}
}
}
// for(i = 0; i < n; i++){
// for(j = 0; j < n; j++){
// cout << cost[i][j] << " ";
// }
// cout << endl;
// }
PathDijkstra(cost, 5, 0, dist, pre);
for(i = 1; i < n; i++){
cout << dist[i] << " ";
}
}