• AcWing 850. Dijkstra求最短路 II 堆优化版 优先队列 稀疏图


    //稀疏图 点和边差不多
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    #include <queue>
    using namespace std;
    typedef pair<int, int> PII;
    const int N = 1e5 + 10;
    int n, m;
    int h[N], e[N], ne[N], idx;
    int w[N];//表示权值
    int dist[N];
    bool st[N];
    void add(int a, int b, int c) {
        e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
    }
    int dijkstra() {
        memset(dist, 0x3f, sizeof dist);
        dist[1] = 0;
        priority_queue<PII, vector<PII>, greater<PII>> heap;//小根堆
        heap.push({0, 1});//起点到起点的距离为0
        while (heap.size()) {
            auto t = heap.top();//找到距离最小的点 
            heap.pop();//删掉 
            int ver = t.second, distance = t.first;
            if (st[ver]) continue;//如果这个点之前已经出来过,就跳过 
            st[ver] = true;// 
            for (int i = h[ver]; i != -1; i = ne[i]) {//遍历所有临边 
                int j = e[i];
                if (dist[j] > distance + w[i]) {
                    dist[j] = distance + w[i];
                    heap.push({dist[j], j});
                }
            }
        }
        if (dist[n] == 0x3f3f3f3f) return -1;
        return dist[n];
    }
    int main() {
        scanf("%d%d", &n, &m);
        memset(h, -1, sizeof h);
        while (m -- ) {
            int a, b, c;
            scanf("%d%d%d", &a, &b, &c);
            add(a, b, c);
        }
        cout << dijkstra() << endl;
        return 0;
    }
  • 相关阅读:
    Android webview 应用
    Android 访问权限设置
    Android应用----如何让应用全屏
    PHP基础
    递归在PHP中的应用举例
    软工实践个人总结
    2020软件工程实践第2次结对编程作业
    2020软件工程第一次结对作业
    2020软件工程实践第一次个人编程作业
    A brief introduction of myself
  • 原文地址:https://www.cnblogs.com/QingyuYYYYY/p/11842152.html
Copyright © 2020-2023  润新知