acwing 849 Dijkstra shortest I beg template

Address  https://www.acwing.com/problem/content/description/851/

Given a point n and m edges directed graph, there may be multiple edges in FIG loopback and all are positive edge weights.

Please find the shortest distance from point 1 to point number n, n number if you can not go from point 1 point, then output -1.

Input Format

The first line contains the integers n and m.

Next m lines contains three integers x, y, Z, it indicates the presence of a point x to point y directed edge from a side length of z.

Output Format

Output an integer, represents the shortest distance to the point 1 point number n.

If the path does not exist, the output of -1.

data range

. 1 n- 500 1≤n≤500,
. 1 m 10 . 5 1≤m≤105,
FIG relates to a side not more than 10,000.

```

Sample input:

3 3
1 2 2
2 3 1
1 3 4

Sample output:

3

```

#include <iostream>
#include <vector>
#include <algorithm>
#include <memory.h>


using namespace std;

const int MAX_N = 1010;

int gra[MAX_N][MAX_N];
int st[MAX_N];
int dist[MAX_N];
int n, m;

int solve()
{
    memset(dist, 0x3f3f3f3f, sizeof(dist));
    dist[1] = 0;

    //循环n-1 轮即可
    for (int i = 0; I <n-- . 1 ; I ++ ) {
         int nearestNode = - . 1 ;
         // find the nearest point 
        for ( int J = . 1 ; J <= n-; J ++ ) {
             IF (ST [J] == 0 && ( == nearestNode - . 1 || dist [nearestNode]> dist [J])) { 
                nearestNode = J; 
            } 
        } 

        // with the distance from the first point of the dot to update the other points 
        for ( int J = . 1 ; J < n-=; J ++ ) { 
            dist [J]Min = (dist [J], dist [nearestNode] + GRA [nearestNode] [J]); 
        } 


        ST [nearestNode] = . 1 ; 
    } 

    // if the number n from the point that it is not updated unreachable 
    IF (dist [n ] == 0x3f3f3f3f ) return - 1 ;
     // returns the number from 1 to n last updated 
    return dist [n]; 
} 

int main () 
{ 
    CIN >> n >> m;
     // All initialization FIG side length is 0x3f3f3f3f 
    Memset (GRA, 0x3F , the sizeof GRA);
     for ( int I = 0; i < m; i++) {
        int a, b, c;
        scanf("%d %d %d",&a,&b,&c);
        //防止重边
        gra[a][b] = min(gra[a][b], c);
    }

    printf("%d\n",solve() ); 

    return 0;
}

 

Guess you like

Origin www.cnblogs.com/itdef/p/12050003.html