#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>

using namespace std;

const int MAXINT = 32767;
const int MAXNUM = 10;
int dist[MAXNUM];
int prev[MAXNUM];
int len;
int v00 = 0;
int A[MAXNUM][MAXNUM];

void input(){
cin >> len;
for (int i = 0 ; i < len ; i++){
for (int j = 0 ; j < len ; j++){
int a;
cin >> a;
A[i][j] = a;
}
}
}

void Dijkstra(int v0)
{
bool S[MAXNUM]; // 判断是否已存入该点到S集合中
int n=MAXNUM;
for(int i=0; i<n; ++i) {
dist[i] = A[v0][i];
S[i] = false; // 初始都未用过该点
if(dist[i] == MAXINT)
prev[i] = -1;
else
prev[i] = v0;
}
dist[v0] = 0;
prev[v0] = -1;
S[v0] = true;
for(int i=1; i<len; i++){
int mindist = MAXINT;
int u = v0; // 找出当前未使用的点j的dist[j]最小值
for(int j=0; j<len; ++j){
if((!S[j]) && dist[j]<mindist){
u = j; // u保存当前邻接点中距离最小的点的号码
mindist = dist[j];
}
}
S[u] = true;
for(int j=0; j<len; j++){
if((!S[j]) && A[u][j]<MAXINT){
if(dist[u] + A[u][j] < dist[j]) //在通过新加入的u点路径找到离v0点更短的路径
{
dist[j] = dist[u] + A[u][j]; //更新dist
prev[j] = u; //记录前驱顶点
}
}
}
}
}

void output(){
for(int i = 0 ; i < len ; i++){
cout <<v00<< " to "<< i <<"'s minDis="<< dist[i] <<" path =( ";
std::vector<int> p;
int t = i;
while(t != -1){
//cout << t<<" ";
p.push_back(t);
t = prev[t];
}
//cout << "p size="<<p.size()<<endl;
reverse(p.begin(), p.end());
for(int j = 0 ; j < p.size() ; j++){
cout << p[j] << " ";
}
cout << ")"<<endl;
}
}

int main(){
input();
Dijkstra(v00);
output();
return 0;
}

 

黄世宇/Shiyu Huang's Personal Page:​​https://huangshiyu13.github.io/​