堆优化SPFA

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

#include
#include
#include
#include
#include
#include
#include
#include
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(nextnext+1]]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;
}

void spfa(int s)
{
    dis[s]=0;put(s);
    while(heap_size!=0)
    {
        int x;
        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]+cy])
            {
                dis[y]=dis[x]+c;
                if(located[y]==0)put(y);
                else change(y);
            }
        }
    }
    return;
}

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=1;i<=n;i++)
     dis[i]=maxn;
     spfa(1);
    cout<return 0;
}

你可能感兴趣的:(堆优化)