参考博客:http://www.wutianqi.com/?p=1890
#include <iostream>
using namespace std;
#define max 1<<20 //无穷大
int pre[100]; //p[i]存放路径中i前面一个点
int dis[100]; //到远点的距离
int c[100][100]; //每个点间的距离
int dijkstra(int n, int v){ //v是源点,n是点的个数
bool s[100] = {0}; //表示是否在原点集合中
for(int i = 1; i <= n; i++){ //初始化dis[],s[],pre[]
dis[i] = c[i][v];
s[i] = 0;
if(dis[i] != max){
pre[i] = v;
}
else
pre[i] = 0;
}
dis[v] = 0;
s[v] = 1;
for(int i = 2; i <= n; i++){
int temp = max, u = v;
for(int j = 1; j <= n; j++){ //找到最小的直达源点的点
if(!s[j] && temp > dis[j]){
temp = dis[j];
u = j;
}
}
// cout << "u: " << u << endl;
s[u] = 1; //表示将找的的点放入源点集合
for(int j = 1; j <= n; j++){ //更新u的临边到远点的距离
if(!s[j] && c[j][u] < max){
// cout << "jJJ" << endl;
if(dis[j] > c[j][u] + dis[u]){
dis[j] = c[j][u] + dis[u];
pre[j] = u;
// cout << "j:" << j << endl;
}
}
}
}
return 1;
}
int luxian(int v, int u){ //查找点源点v到u点的距离
int p;
int count = 0, a[100] = {u};
p = pre[u];
while(p != v){
a[++count] = p;
p = pre[p];
}
a[++count] = v;
cout << "count" << count << endl;
for(int i = count; i >= 0; i--)
cout << a[i] << " -> ";
}
int main(){
ios::sync_with_stdio(false);
int n, line, a, b, len;
cin >> n >> line;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
c[i][j] = max;
cout << max;
for(int i = 1; i <= line; i++){
cin >> a >> b >> len;
if(len < c[a][b]){
c[a][b] = len;
c[b][a] = len;
}
}
for(int i = 1; i <= n; i++)
dis[i] = max;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++)
cout << c[i][j] << " ";
cout << endl;
}
dijkstra(n, 1);
luxian(1, n);
cout << endl;
cout << "1到n的最小距离: " << dis[n] << endl;
return 0;
}