Solution: shortest (floyed)

Description Title
to an undirected graph G (U, E), the shortest distance between any two points in the query.
Input
of the first row two integers n, m represents the number of nodes and edges in FIG., The node number from 1 to n.
Next m lines of three integers u, v, w w expressed as a distance between edges of u, v.
The next line an integer q, represents the number of inquiries.
The next two rows each integer q lines u, v, represents the shortest distance interrogation u to v, v if u not reach the outputs -1.
Data range: n <= 100, m < = 5000, q <= 10000, 0 <w <= 1000.
Output corresponding to the output line q answer.
Sample input
. 5 10
. 1 2. 1
2 10. 5
. 1 2 3
. 1. 4. 4
. 1. 5. 6
2 3. 4
2. 4 3
3. 1. 4
3. 4. 5
. 4. 5 2
. 5
. 1. 4
3. 5
2 3
. 4 2
. 5 2
Sample Output
3
. 3
. 3
. 3
. 5
pits: 1, to their own distance is 0;
2, the assignment may be repeated in the same way, it is determined to take a small

#include<bits/stdc++.h>
using namespace std;
const int INF=0x3f3f3f3f;
int a[150][150];
int main()
{
 int n,m,u,v,w,q;
 while(cin>>n>>m)
 {
  for(int i=1;i<=n;i++)
   for(int j=1;j<=n;j++)
    a[i][j]=INF;
  for(int i=1;i<=n;i++)//
    a[i][i]=0;
  for(int i=1;i<=m;i++)
  {
   cin>>u>>v>>w;
   if(w<a[u][v])         //
   a[u][v]=a[v][u]=w; 
 }
 for(int k=1;k<=n;k++)
  for(int i=1;i<=n;i++)
   for(int j=1;j<=n;j++)
    a[i][j]=min(a[i][j],a[i][k]+a[k][j]);
 cin>>q;
 while(q--)
 {
  cin>>u>>v;
  if(a[u][v]<INF) cout<<a[u][v]<<endl;
  else cout<<-1<<endl;
 }
 }
 return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43540515/article/details/91382947