多源最短路-Floyd
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 5 typedef long long ll; 6 const int MAXSIZE=210; 7 const int INF=(int)1e9; 8 9 int matrix[MAXSIZE][MAXSIZE]; 10 int ans[MAXSIZE][MAXSIZE][MAXSIZE]; 11 int n,m,t[MAXSIZE]; 12 13 void Floyd() 14 { 15 for (int k=0;k<n;k++) 16 { 17 for (int i=0;i<n;i++) 18 { 19 for (int j=0;j<n;j++) 20 { 21 matrix[i][j]=min(matrix[i][j],matrix[i][k]+matrix[k][j]); 22 } 23 } 24 25 for (int i=0;i<n;i++) 26 { 27 for (int j=0;j<n;j++) 28 { 29 ans[k][i][j]=matrix[i][j]; 30 } 31 } 32 } 33 return; 34 } 35 36 void query(int x,int y,int d) 37 { 38 if (t[x]>d || t[y]>d) //起点或终点村庄还未重建完成 39 { 40 cout<<"-1"<<endl; 41 return; 42 } 43 else 44 { 45 int ret=INF; 46 for (int k=0;k<n;k++) //遍历x至y的每个中间村庄 47 { 48 if (t[k]<=d && ans[k][x][y]<INF) //中间村庄已重建并且能走通 49 { 50 ret=min(ret,ans[k][x][y]); 51 } 52 } 53 if (ret!=INF) cout<<ret<<endl; 54 else cout<<-1<<endl; 55 } 56 return; 57 } 58 59 int main() 60 { 61 cin>>n>>m; 62 for (int i=0;i<n;i++) 63 { 64 cin>>t[i]; 65 } 66 67 for (int i=0;i<n;i++) 68 { 69 for (int j=0;j<n;j++) 70 { 71 if (i!=j) matrix[i][j]=INF; 72 } 73 } 74 75 int u,v,w; 76 for (int i=0;i<m;i++) 77 { 78 cin>>u>>v>>w; 79 matrix[u][v]=matrix[v][u]=w; 80 } 81 82 Floyd(); 83 84 int q,x,y,d; 85 cin>>q; 86 while (q--) 87 { 88 cin>>x>>y>>d; 89 query(x,y,d); 90 } 91 92 return 0; 93 }