- 5. 弗洛伊德算法求最短路径
【问题描述】
对于下面一张若干个城市,以及城市之间距离的地图,请采用弗洛伊德算法求出所有城市之间的最短路径。
【输入形式】
顶点个数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 <bits/stdc++.h>
using namespace std;
const int inf = 9999;
int arc[55][55];
int n;
int dist[55][55];
vector<int> path[55][55];
void creat()
{
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
cin >> arc[i][j];
if (i == j)
arc[i][j] = 0;
}
}
void floyed()
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
dist[i][j] = arc[i][j];
if (dist[i][j] != inf && i != j)
{
path[i][j].push_back(i);
path[i][j].push_back(j);
}
else if (i == j)
path[i][j].push_back(i);
else
path[i][j].push_back(9999);
}
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (dist[i][j] > dist[i][k] + dist[k][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
path[i][j].clear();
for (int q = 0; q < path[i][k].size() - 1; q++)
{
path[i][j].push_back(path[i][k][q]);
}
for (int q = 0; q < path[k][j].size(); q++)
{
path[i][j].push_back(path[k][j][q]);
}
}
}
void show()
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (i == j)
{
dist[i][j] = 0;
path[i][j].clear();
path[i][j].push_back(i);
}
cout << "from " << i << " to " << j << ": "
<< "dist = " << dist[i][j] << " path:";
for (int k = 0; k < path[i][j].size(); k++)
{
cout << path[i][j][k] << " ";
}
cout << endl;
}
}
int main()
{
creat();
floyed();
show();
}