【题解】
求任意两点间的最短路径。此题数据量较小,用Floyd算法,时间复杂度为O(n^3)。
参考https://blog.csdn.net/qq_34594236/article/details/64971883
【代码】
#include <iostream>
#include <map>
#include <string>
#define maxn 50
#define INF 100000
using namespace std; int dist[][], path[][];
map<string, int> map1;
map<int, string>map2; void init()
{
int P, Q;
string scene;
for (int i = ; i < maxn; i++) {
for (int j = ; j < maxn; j++) {
dist[i][j] = INF;
path[i][j] = j; // denotes the next point from point i on the shortest path from i to j
}
dist[i][i] = ;
}
cin >> P;
for (int i = ; i < P; i++) {
cin >> scene;
map1[scene] = i;
map2[i] = scene;
}
cin >> Q;
for (int i = ; i < Q; i++) {
string t1, t2;
int d;
cin >> t1 >> t2 >> d;
dist[map1[t1]][map1[t2]] = dist[map1[t2]][map1[t1]] = d;
}
} void floyd()
{
for(int k = ; k < maxn; k++)
for(int i = ; i < maxn; i++)
for (int j = ; j < maxn; j++) {
if (dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
path[i][j] = path[i][k];
}
}
} int main()
{
int R;
init();
floyd();
cin >> R;
for (int i = ; i < R; i++) {
string t1, t2;
int k;
cin >> t1 >> t2;
if (t1 == t2) {
cout << t1 << endl;
continue;
}
k = path[map1[t1]][map1[t2]];
cout << t1 << "->(" << dist[map1[t1]][k] << ")->";
while (k != map1[t2]) {
cout << map2[k] << "->(" << dist[k][path[k][map1[t2]]] << ")->";
k = path[k][map1[t2]];
}
cout << t2 << endl;
}
//system("pause");
return ;
}