您的位置:首页 > 其它

堆优化prim

2016-03-13 13:16 316 查看
#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 ans;
int k;
struct node{
int num;
node(){}
node(int h){num=h;}
bool operator <(const node & p)const
{
return dis[p.num]<dis[num];
}
};
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();ans+=dis[x];
for(int j=last[x];j;j=e[j].zhi)
{
int y=e[j].next;
int c=e[j].c;
if(c<dis[y])
{
dis[y]=c;
change(y);
}
}
}
cout<<ans<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: