Yibentong Part Three Data Structure Chapter Four Graph Theory Algorithm Section Two Shortest Path Algorithm 1378: Shortest Path (shopth)

1378: The shortest path (shopth)

Time limit: 1000 ms Memory limit: 65536 KB
Number of submissions: 1299 Number of passes: 469
[Title description]
Given a directed graph G=(V, E), and a source point v0∈V, please write a program to output v0 And the shortest path of other vertices in graph G. As long as the sum of the weights of all directed rings are positive, we allow the edges of the graph to have negative values. The vertices are numbered from 1 to n (n is the number of vertices in the graph G).

[Input]
Line 1: A positive number n (2≤n≤80), which represents the total number of vertices in the graph G.

Line 2: An integer representing the source point v0 (v0∈V, v0 can be any vertex in the graph G).

In the 3rd to n+2th rows, this graph is given by an adjacency matrix W.

[Output]
A total of n-1 lines are included. In the order of vertex number from small to large, each line outputs the shortest distance from the source point v0 to a vertex. Refer to the sample for the specific format of each line.

【Input example】
5
1
0 2--10

  • 0 3 - 7
    • 0 4 -
      • 0 5
    • 6--0
      [] Output Sample
      (1 -> 2) = 2
      (1 -> 3) 5 =
      (1 -> 4) 9 =
      (1 -> 5) = 9
      [Note]
      sample as corresponding to FIG. :
#include<iostream>
#include<cstdio>
#define INF 0x3f3f3f3f
using namespace std;
int a[10001][10001];
int main()
{
    
    
    int n,s;
    cin>>n>>s;
    for(int i=1;i<=n;i++)
    {
    
    
        for(int j=1;j<=n;j++)
        {
    
    
            int b;
            if(scanf("%d",&b)==1)
                a[i][j]=b;
            else
                a[i][j]=INF;
        }
    }
 
    for(int k=1;k<=n;k++)
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                if(a[i][j]>a[i][k]+a[k][j])
                    a[i][j]=a[i][k]+a[k][j];
 
    for(int i=1;i<=n;i++)
        if(i!=s)
			cout<<"("<<s<<" -> "<<i<<") = "<<a[s][i]<<endl;
 
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44043668/article/details/86072186