堆优化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; }
相关文章推荐
- jvm 锁原理
- pintuer e.handler.apply is not a function
- hdoj--2186--悼念512汶川大地震遇难同胞——一定要记住我爱你(模拟水题)
- 经典排序算法——归并排序
- hdoj--2186--悼念512汶川大地震遇难同胞——一定要记住我爱你(模拟水题)
- 《构建之法》阅读笔记02
- caffe 输出重定向, 双重输出重定向
- MySQL数据库总结(6)列类型及列的增删改
- Java 二维数组实现杨辉三角
- Annotation--java注解
- loadrunner Fast learning First Day
- BZOJ_P2152 聪聪可可(点分治)
- 杭电oj 2012 素数判定
- hdoj--2073--无限的路(数学规律)
- 剑指offer:数组中只出现一次的数字
- [PHP]向类中动态添加数据
- 那些年我们开发的应用程序
- Activity生命周期解说
- 实验三:gdb跟踪调试内核从start_kernel到init进程启动
- hdoj--2073--无限的路(数学规律)