对于下面一张若干个城市,以及城市之间距离的地图,请采用弗洛伊德算法求出所有城市之间的最短路径。
【输入形式】
顶点个数n,以及n*n的邻接矩阵,其中不可达使用9999代替
【输出形式】
每两个顶点之间的最短路径和经过的顶点
注意:顶点自身到自身的dist值为0,path则为该顶点的编号
【样例输入】
4
9999 4 11 9999
6 9999 2 9999
1 9999 9999 1
9999 3 9999 9999
【样例输出】
from 0 to 0: dist = 0 path:0
from 0 to 1: dist = 4 path:0 1
from 0 to 2: dist = 6 path:0 1 2
from 0 to 3: dist = 7 path:0 1 2 3
from 1 to 0: dist = 3 path:1 2 0
from 1 to 1: dist = 0 path:1
from 1 to 2: dist = 2 path:1 2
from 1 to 3: dist = 3 path:1 2 3
from 2 to 0: dist = 1 path:2 0
from 2 to 1: dist = 4 path:2 3 1
from 2 to 2: dist = 0 path:2
from 2 to 3: dist = 1 path:2 3
from 3 to 0: dist = 6 path:3 1 2 0
from 3 to 1: dist = 3 path:3 1
from 3 to 2: dist = 5 path:3 1 2
from 3 to 3: dist = 0 path:3
#include<iostream>
#include<vector>
#define maxsize 100
using namespace std;
int n;
int dist[maxsize][maxsize];
vector<int> path[maxsize][maxsize];
vector<int> JoinList(int i,int k,int j)//合并路径
{
path[i][j].clear();
int tail = path[i][k].back();
path[i][k].pop_back();
vector<int>temp;
for (int m = 0; m < (signed)path[i][k].size(); m++)
{
temp.push_back(path[i][k][m]);
}
for (int n = 0; n < (signed)path[k][j].size(); n++)
{
temp.push_back(path[k][j][n]);
}
path[i][k].push_back(tail);
return temp;
}
void flyd()
{
for (int i = 0; i < n; i++)//初始化dist[i][j]与path[i][j]
{
for (int j = 0; j < n; j++)
{
cin >> dist[i][j];
if (dist[i][j] < 9999)
{
path[i][j].push_back(i);
path[i][j].push_back(j);
}
else if(i==j&&dist[i][j]==9999)//对角线上path填一个顶点即可
{
path[i][j].push_back(i);
}
}
}
for (int k = 0; k < n; k++)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (dist[i][k] + dist[k][j] < dist[i][j]&&i!=j)//顶点自身无法到达
{
dist[i][j] = dist[i][k] + dist[k][j];
path[i][j] = JoinList(i,k,j);
}
}
}
}
}
void printAns()
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (dist[i][j] == 9999) dist[i][j] = 0;
cout << "from " << i << " to " << j << ": " << "dist = " << dist[i][j] << " path:";
for (int k = 0; k < (signed)path[i][j].size();k++)
{
cout<<path[i][j][k]<<" ";
}
cout << endl;
}
}
}
int main()
{
cin >> n;
flyd();
printAns();
//system("pause");
return 0;
}