850. Dijkstra's shortest path II + heap optimization version

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 non-negative.

Please find the shortest distance from point 1 to point n. If it is impossible to go from point 1 to point n, output −1.

Input format
The first line contains integers n and m.

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

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

If the path does not exist, output −1.

The data range is
1≤n, m≤1.5×105, and
the lengths of the sides involved in the figure are not less than 0 and not more than 10000.

Input sample:
3 3
1 2 2
2 3 1
1 3 4
Output sample:
3

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int h[N], e[N], ne[N], w[N], idx;
typedef pair<int, int> PII;
int n, m;
int dist[N];
int vis[N];

void add(int a, int b, int c)
{
    
    
    e[idx] = b;
    ne[idx] = h[a];
    w[idx] = c;
    h[a] = idx++;
}

int dijkstra()
{
    
    
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    
    //优先队列模拟堆, greater<> 表示数字越小优先级越大, less< >表示数字越大优先级越大
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({
    
    0, 1});
    
    while(heap.size()) {
    
    
        auto t = heap.top();
        heap.pop();
        
        int v = t.second, d = t.first;
        if(vis[v]) continue;
        vis[v] = true;
        
        for(int i = h[v]; i!= -1; i = ne[i]) {
    
    
            int j = e[i];
            if(dist[j] > dist[v] + w[i]) {
    
    
                dist[j] = dist[v] + w[i];
                heap.push({
    
    dist[j], j});
            }
            
        }
    }
    
    if(dist[n] == 0x3f3f3f3f) return -1;
    else return dist[n];
}

int main()
{
    
    
    //初始化
    memset(h, -1, sizeof h);
    
    cin >> n >> m;
    int a, b, c;
    for(int i=0; i<m; i++) {
    
    
        cin >> a >> b >> c;
        add(a, b, c);
    }
    
    cout << dijkstra() << endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324129044&siteId=291194637