[OI - 模板] 堆优化Dijkstra

Posted aiyi2000

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[OI - 模板] 堆优化Dijkstra相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
 
using namespace std;
//#define DEBUG(x) cerr << #x << "=" << x << endl
const int maxn = 1e6 + 10;

struct Edge
{ 
    int v;
    int w;
    int nxt; 
}e[maxn];

struct node 
{
    int u, d;
    bool operator <(const node& rhs) const 
    {
        return d > rhs.d;
    }
};

int head[maxn], cnt = 0;
int n, m;
int dis[maxn];

inline void addEdge(int u, int v, int w) 
{
    e[++cnt].v = v;
    e[cnt].w = w;
    e[cnt].nxt = head[u];
    head[u] = cnt;
}

inline void Dijkstra() 
{
    for (register int i = 1; i <= n; i++) dis[i] = 0x7fffffff;
    dis[1] = 0;
    priority_queue<node> Q;
    Q.push((node){1,0});    
    while (!Q.empty()) 
    {
        node fr = Q.top(); 
        Q.pop();
        int u = fr.u;
        int d = fr.d;
        if (d != dis[u]) continue;
        for (register int i = head[u]; i; i = e[i].nxt) 
        {
            int v = e[i].v;
            int w = e[i].w;
            if (dis[u] + w < dis[v]) 
            {
                dis[v] = dis[u] + w;
                Q.push((node){v,dis[v]});
            }
        }
    }
}

int main()  
{
    scanf("%d%d", &n, &m);
    for (register int i = 1; i <= m; i++) 
    {
        int x, y, z;
        scanf("%d%d%d", &x, &y, &z);
        addEdge(x, y, z);
        addEdge(y, x, z);
    }
    Dijkstra();
    printf("%d
", dis[n]);
    return 0;
}

以上是关于[OI - 模板] 堆优化Dijkstra的主要内容,如果未能解决你的问题,请参考以下文章

dijkstra堆优化模板

hdu 2544 单源最短路问题 dijkstra+堆优化模板

[模板] dijkstra (堆优化)

P4779 模板单源最短路径(标准版)二叉堆优化的 Dijkstra

HDU 2544 - 最短路 - [堆优化dijkstra][最短路模板题]

堆优化dijkstra+set优化dijkstra