用邻接矩阵来存储
Floyd算法原理是动态规划
d[k, i, j]表示:从i这个点,只经过从1~k这些点,到达j点的最短距离
然后k这一维可以去掉
Floyd算法可以有负权,但不能有负权回路,不然最短距离会变成负无穷
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int N = 210, INF = 1e9; 4 int d[N][N]; 5 int n, m, k; 6 void floyd() { 7 for (int k = 1; k <= n; k++) { //首先枚举k,k是阶段 8 for (int i = 1; i <= n; i++) { 9 for (int j = 1; j <= n; j++) { 10 d[i][j] = min(d[i][j], d[i][k] + d[k][j]); 11 } 12 } 13 } 14 } 15 //结束后,d[i][j]存的就是从i到j的最短路的长度 16 int main() { 17 cin >> n >> m >> k; 18 for (int i = 1; i <= n; i++) { 19 for (int j = 1; j <= n; j++) { 20 if (i == j) { 21 d[i][j] = 0; 22 } else { 23 d[i][j] = INF; 24 } 25 } 26 } 27 while (m--) { 28 int a, b, w; 29 cin >> a >> b >> w; 30 d[a][b] = min(d[a][b], w); 31 } 32 floyd(); 33 while (k--) { 34 int a, b; 35 cin >> a >> b; 36 if (d[a][b] > INF / 2) { 37 cout << "impossible" << endl; 38 } else { 39 cout << d[a][b] << endl; 40 } 41 } 42 return 0; 43 }