You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1003;
int g[N][N], path[N][N]; // 邻接矩阵、路径
int n, x, y, w[N]; // 额外费用
void floyd() {
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
if (g[i][k] != INF)
for (int j = 1; j <= n; j++) {
if (g[i][j] > g[i][k] + g[k][j] + w[k]) {
g[i][j] = g[i][k] + g[k][j] + w[k];
path[i][j] = path[i][k];
}
if (g[i][j] == g[i][k] + g[k][j] + w[k]) {
if (path[i][j] > path[i][k]) // 字典序
path[i][j] = path[i][k];
}
}
}
int main() {
while (cin >> n && n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
path[i][j] = j; // 路径初始化,如果i->j有边则记录path[i][j]=j,就是记录i->j的中间节点
cin >> g[i][j];
if (g[i][j] == -1) g[i][j] = INF;
}
}
for (int i = 1; i <= n; i++) cin >> w[i];
floyd();
while (cin >> x >> y) {
if (x == -1 && y == -1) break;
printf("From %d to %d :\n", x, y);
printf("Path: %d", x);
int u = x, v = y;
// 用循环打印路径
while (x != y) {
printf("-->%d", path[x][y]);
x = path[x][y];
}
puts("");
if (g[u][v] < INF)
printf("Total cost : %d\n", g[u][v]);
else
puts("-1");
puts("");
}
}
return 0;
}