原题链接:
题解:
对于求多源最短路径问题,直接用Floyd算法三个循环暴力求解即可
代码:
#include<bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int n, m, q;
const int N = 2e2 + 10;
int d[N][N];
void floyd() {
for (int k = 1;k <= n;k++)
for (int i = 1;i <= n;i++)
for (int j = 1;j <= n;j++)
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
int main() {
cin >> n >> m >> q;
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= n;j++) {
if (i == j) d[i][j] = 0;
else d[i][j] = INF;
}
}
for (int i = 0;i < m;i++) {
int x, y, z;cin >> x >> y >> z;
d[x][y] = min(d[x][y], z);
}
floyd();
while (q--) {
int x, y;cin >> x >> y;
if (d[x][y] > INF / 2) cout << "impossible" << endl;
else cout << d[x][y] << endl;
}
}