多源求最短路
#include<iostream> #include<algorithm> #include<cstring> using namespace std ; typedef long long LL ; const LL N = 410 , INF = 0x3f3f3f3f3f3f3f3f;//最大值 LL f[N][N] ; LL n , m , q ; int main(){ cin >> n >> m >> q ; for(int i = 1 ; i <= n ;i ++){ for(int j =1 ; j <= n ; j ++){ f[i][j] = INF ; } } for(int i = 1 ; i <= m ; i++){ LL a, b, c ; cin >> a >> b >> c ; f[a][b] = f[b][a] = min(c,f[a][b]) ;//可能有重边 } for(int k = 1 ; k <= n ; k++){ for(int i = 1 ; i <= n ; i ++){ for(int j = 1 ; j <= n ; j ++){ f[i][j] = min(f[i][j] , f[i][k] + f[k][j]) ; } } } for(int i = 1 ; i <= q ; i ++){ LL a , b ; cin >> a >> b ; if(f[a][b] == INF) cout << "-1" << endl ;//如果没更新过,就说明没有公共边,就输出-1 else if(a == b) cout << "0" << endl ;//如果相等就输出0 else cout << f[a][b] << endl ; } return 0 ; }