- 时间复杂度O(n^3)
- 动态规划
- d[k][i][j] = min(d[k-1][i][j],d[k-1][i][k] + d[k-1][k][j])
- 可以简化为
d[i][j] = min(d[i][j], d[i][k] + d[j][k]) //考虑经过k点时的最短路
代码
cpp
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int N = 210;
int g[N][N];
int n;
void floyed(){
for(int k = 1; k <= n; k++){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
}
}
}
}
int main(){
int m,k;
cin>>n>>m>>k;
int x, y, z;
//考虑重边和自环
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(i == j){
g[i][j] = 0; //去掉环
}else g[i][j] = 0x3f3f3f3f;
}
}
for(int i = 0; i < m; i++){
cin>>x>>y>>z;
g[x][y] = min(g[x][y],z);
}
int a, b;
int ans;
floyed();
for(int i = 0; i < k; i++){
cin>>a>>b;
if(g[a][b] > 0x3f3f3f3f/2){
cout<<"impossible" << '\n';
}else cout<< g[a][b]<< '\n';
}
return 0;
}