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.

56 lines
1.7 KiB

#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1003;
int mp[N][N], path[N][N]; // 邻接矩阵、路径
int n, x, y, u, v, cost[N]; // 额外费用
void floyd() {
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
if (mp[i][k] != INF)
for (int j = 1; j <= n; j++) {
if (mp[i][j] > mp[i][k] + mp[k][j] + cost[k]) {
mp[i][j] = mp[i][k] + mp[k][j] + cost[k];
path[i][j] = path[i][k];
}
if (mp[i][j] == mp[i][k] + mp[k][j] + cost[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;
cin >> mp[i][j];
if (mp[i][j] == -1) mp[i][j] = INF;
}
}
for (int i = 1; i <= n; i++) cin >> cost[i];
floyd();
while (cin >> x >> y) {
if (x == -1 && y == -1) break;
u = x, v = y;
printf("From %d to %d :\n", x, y);
printf("Path: %d", x);
while (x != y) {
printf("-->%d", path[x][y]);
x = path[x][y];
}
printf("\n");
if (mp[u][v] < INF)
printf("Total cost : %d\n", mp[u][v]);
else
printf("-1\n");
printf("\n");
}
}
return 0;
}