堆优化Dijkstra 模版

#include <cstdio>
#include <algorithm>
using namespace std;
const int inf=1000000000;
int n,m,top,idx,s;
int to[2000001],next[2000001],len[2000001],head[100001],
    h[131073],pos[100001],d[100001];
bool v[100001];
void add(int x,int y,int z)
{
    to[++idx]=y;
    len[idx]=z;
    next[idx]=head[x];
    head[x]=idx;

    to[++idx]=x;
    len[idx]=z;
    next[idx]=head[y];
    head[y]=idx;
    return ;
}
void pushup(int x)
{
    while(x>1)
    {
        if(d[h[x]]<d[h[x>>1]])
            swap(h[x],h[x>>1]),
            swap(pos[h[x]],pos[h[x>>1]]),
            x>>=1;
        else
            break;
    }
    return ;
}
void insert(int x)
{
    h[++top]=x;
    pos[x]=top;
    pushup(top);
    return ;
}
void pop()
{
    pos[h[1]]=0;
    h[1]=h[top--];
    if(top)
        pos[h[1]]=1;
    int x=2;
    while(x<=top)
    {
        if(d[h[x]]>d[h[x+1]])
            ++x;
        if(d[h[x]]<d[h[x>>1]])
            swap(h[x],h[x>>1]),
            swap(pos[h[x]],pos[h[x>>1]]),
            x<<=1;
        else
            break;
    }
    return ;
}
void dijkstra()
{
    for(int i=1;i<=n;++i)
        d[i]=inf;
    d[s]=0;
    insert(s);
    while(top)
    {
        int x=h[1];pop();
        if(v[x])
            continue;
        v[x]=true;
        for(int i=head[x];i;i=next[i])
            if(!v[to[i]]&&d[to[i]]>d[x]+len[i])
            {
                d[to[i]]=d[x]+len[i];
                insert(to[i]);
            }
    }
    return ;
}
int main()
{
    s=1;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;++i)
    {
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
    }
    dijkstra();
    printf("%d",d[n]);
    return 0;
}
    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/A_E_Lv_0_0_/article/details/52843581
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞