代码
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
const int N = 210, INF = 1e9;
int n, m, Q;
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;
}
}
}
while (m--) {
int a, b, c;
cin >> a >> b >> c;
d[a][b] = min(d[a][b], c);
}
floyd();
while (Q--) {
int a, b;
cin >> a >> b;
int t = d[a][b];
if (t > INF / 2) {
cout << "impossible" << endl;
}
else {
cout << t << endl;
}
}
return 0;
}
若i=4,j=3,k=2,那么d[4,3]=min(d[4,3],d[4,2]+d[2,3]),按照遍历顺序,d[4,2]和d[2,3]都是更新过的啊,这不就不符合要求了吗?可以解释一下为什么可以去掉一维吗?
知道了,d[k-1 i k] 、d[k-1 k j]和 d[k i k]、 d[k k j]等价
卧槽,《算法进阶指南》中的原话
我手敲了一遍, 记个笔记