堆优化Dijkstra

题目:http://acm.zjnu.edu.cn/CLanguage/showproblem?problem_id=1211

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<climits>
using namespace std;
#define maxn 99999999
struct E{
    int next;
    int c;
    int zhi;
}e[1005000];

inline int read()
{
  char ls=getchar();for (;ls<'0'||ls>'9';ls=getchar());
  int x=0;for (;ls>='0'&&ls<='9';ls=getchar()) x=x*10+ls-'0';
  return x;
}
int last[100500];
int dis[100500];
int n,m;
int k;
int located[100500];
int heap[300500];
int heap_size;
inline void put(int d)
{
    int now,next;
    heap[++heap_size]=d;
    now=heap_size;
    located[d]=now;
    while(now>1)
    {
        next=now>>1;
        if(dis[heap[now]]>=dis[heap[next]])break;
        located[d]=next;
        located[heap[next]]=now;
        swap(heap[now],heap[next]);
        now=next;
    }
    return;
}
inline void change(int d)
{
    int now,next;
    now=located[d];
    while(now>1)
    {
        next=now>>1;
        if(dis[heap[now]]>=dis[heap[next]])break;
        located[d]=next;
        located[heap[next]]=now;
        swap(heap[now],heap[next]);
        now=next;
    }
    return;
}
inline int get()
{
    int now,next,res;
    res=heap[1];
    heap[1]=heap[heap_size--];
    now=1;
    located[heap[1]]=1;
    located[res]=0;
    while(now*2<=heap_size)
    {
        next=now*2;
        if(next<heap_size&&dis[heap[next+1]]<dis[heap[next]])++next;
        if(dis[heap[now]]<=dis[heap[next]])break;
        located[heap[now]]=next;
        located[heap[next]]=now;
        swap(heap[next],heap[now]);
        now=next;
    }   
    return res;
}

int main()
{
    n=read(),m=read();
    for(int i=1;i<=m;i++)
        {
            int a1,b1,c1;
            a1=read();b1=read();c1=read();
            e[++k].next=b1;
            e[k].c=c1;
            e[k].zhi=last[a1];
            last[a1]=k;

            e[++k].next=a1;
            e[k].c=c1;
            e[k].zhi=last[b1];
            last[b1]=k;
        }
    for(int i=2;i<=n;i++)
    dis[i]=maxn;
    for(int j=last[1];j;j=e[j].zhi)
    {
        int y=e[j].next;
        int c=e[j].c;
        if(c<dis[y])dis[y]=c;
    }
    for(int i=2;i<=n;++i)
    put(i);

    for(int i=1;i<=n-1;++i)
    {
        int x=get();
        for(int j=last[x];j;j=e[j].zhi) 
        {
            int y=e[j].next;
            int c=e[j].c;
            if(dis[x]+c<dis[y])
            {
                dis[y]=dis[x]+c;
                change(y);
            }
        }
    }
    cout<<dis[n]<<endl;
    return 0;
}
    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/cym19981017/article/details/50877194
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞