Dijkstra finds the shortest path Ⅰ

Dijkstra finds the shortest path Ⅰ


from acwing849
Time limit:1s
Memory limit:64MB

Problem Description

Given a directed graph with n points and m edges, there may be multiple edges and self-loops in the graph, and all edge weights are positive.

Please find the shortest distance from point 1 to point n. If you cannot walk from point 1 to point n, output -1.

Input

The first line contains integers n and m.

Each of the next m rows contains three integers x, y, z, indicating that there is a directed edge from point x to point y, and the length of the side is z.

Output

Output an integer, representing the shortest distance from point 1 to point n.

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

data range

1≤n≤5001≤n≤500,
1≤m≤1051≤m≤105, the
length of the sides involved in the figure does not exceed 10,000.

Sample Input

3 3
1 2 2
2 3 1
1 3 4

Sample Output

3

Pay attention to directed graphs and double edges.

#include<cstdio>
#include<cstring>
using namespace std;
int mp[505][505],dis[505];               //mp存储地图,dis是距离状态
bool note[505];                          //后续dij算法查看某个点是否已经被选取过
int n,m;                                 //点、边
void init(){
    
                                //初始化
    scanf("%d %d",&n,&m);
    memset(mp,0x3f,sizeof(mp)),memset(note,false,sizeof(note));
    int f,t,w;
    for(int i = 1;i <= m;++i){
    
    
        scanf("%d %d %d",&f,&t,&w);
        if(mp[f][t] > w)
            mp[f][t] = w;
    }
    for(int i = 2;i <= n;++i)
        dis[i] = mp[1][i];
    dis[1] = 0;note[1] = true;
}
void solve(){
    
    
    for(int i = 2;i <= n;++i){
    
          //dijkstra
        int mi = 0x3f3f3f3f,k = -1;
        for(int j = 2;j <= n;++j)
            if(!note[j] && mi > dis[j])
                mi = dis[j],k = j;
        if(k == -1)
            break;
        note[k] = true;
        for(int j = 2;j <= n;++j)
            if(dis[j] > dis[k] + mp[k][j])
                dis[j] = dis[k] + mp[k][j];
    }
    if(dis[n] == 0x3f3f3f3f)
        printf("-1");
    else
        printf("%d",dis[n]);
}
int main(){
    
    
    init();
    solve();
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45985728/article/details/113704330