current position:Home>Dijkstr heap optimization

Dijkstr heap optimization

2022-08-06 08:55:20ThXe

typedef pair<int, int> PII;
const int N = 1e6 + 10;
struct DIJKSTRA {
    
    int n, m;
    int h[N], w[N], e[N], ne[N], idx;
    int dist[N];
    bool st[N];
    void init() {
    
        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);
        }
    }
    void add(int a, int b, int c)
    {
    
        e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
    }

    int dijkstra(int s,int end)
    {
    
        memset(dist, 0x3f, sizeof dist);
        dist[s] = 0;
        priority_queue<PII, vector<PII>, greater<PII>> heap;
        heap.push({
     0, s });

        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] > dist[ver] + w[i])
                {
    
                    dist[j] = dist[ver] + w[i];
                    heap.push({
     dist[j], j });
                }
            }
        }

        if (dist[end] == 0x3f3f3f3f) return -1;
        return dist[end];
    }
    void output() {
    
        cout << dijkstra(1, n) << endl;
    }
}Dij;//mlogn

copyright notice
author[ThXe],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/218/202208060847341565.html

Random recommended