时间复杂度:AcWing854. Floyd求最短路 - 图1,可以求解多源最短路,可能含有负权的图等问题。

    1. #include<iostream>
    2. #include<algorithm>
    3. #include<cstring>
    4. using namespace std;
    5. const int N = 510, INF = 1e9+10;
    6. int dist[N][N];
    7. int n,m,Q;
    8. void floyd(){
    9. for(int k=1;k<=n;k++){
    10. for(int i=1;i<=n;i++){
    11. for(int j=1;j<=n;j++){
    12. dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j]);
    13. }
    14. }
    15. }
    16. }
    17. int main(){
    18. cin >> n >> m >> Q;
    19. for(int i=1;i<=n;i++){
    20. for(int j=1;j<=n;j++){
    21. // 注意自环
    22. if(i==j) dist[i][j] = 0;
    23. else dist[i][j] = INF;
    24. }
    25. }
    26. while(m--){
    27. int a,b,c;
    28. cin >> a >> b >> c;
    29. // 避免重边
    30. dist[a][b] = min(dist[a][b],c);
    31. }
    32. floyd();
    33. while(Q--){
    34. int a,b;
    35. cin >> a >> b;
    36. if(dist[a][b]>INF/2) puts("impossible");
    37. else cout << dist[a][b] << endl;
    38. }
    39. return 0;
    40. }