学过一些dp后,比较容易理解floyd,也比较好记。
稍微有点不理解,一般dp从n维降到n-1维,三层for循环中的最里面两层循环,一般下标是从大到小。
需反复理解
且Floyd也可同之前的一起求边权为负的图的最短路。
#include <iostream>
#include <cstring>
#include <algorithm>
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(){
scanf("%d%d%d",&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;
scanf("%d%d%d",&a,&b,&c);
d[a][b] = min(d[a][b],c);//去除重边
}
floyd();
while(q--){
int a,b;
scanf("%d%d",&a,&b);
if(d[a][b] > INF / 2) puts("impossible");
else printf("%d\n",d[a][b]);
}
return 0;
}