您的位置:首页 > 其它

HDU 1512 Monkey King 并查集+左偏树

2016-10-27 09:07 375 查看
时空隧道

代码如下:

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
//by NeighThorn
using namespace std;
const int maxn=100000+5;
int n,m,fa[maxn],root[maxn];
struct M{
int l,r,val,dis;
}heap[maxn];
inline int find(int x){
return x==fa[x]?x:fa[x]=find(fa[x]);
}
inline int merge(int x,int y){
if(!x||!y)
return x+y;
if(heap[x].val<heap[y].val)
swap(x,y);
int &l=heap[x].l,&r=heap[x].r;
r=merge(r,y);
if(heap[l].dis<heap[r].dis)
swap(heap[x].l,heap[x].r);
if(r)
heap[x].dis=heap[r].dis+1;
else
heap[x].dis=0;
return x;
}
inline int pop(int x){
int l=heap[x].l,r=heap[x].r;
heap[x].l=heap[x].r=heap[x].dis=0;
return merge(l,r);
}
signed main(void){
while(scanf("%d",&n)!=EOF){
int x,y;
for(int i=1;i<=n;i++)
scanf("%d",&heap[i].val),fa[i]=root[i]=i,heap[i].l=heap[i].r=heap[i].dis=0;
scanf("%d",&m);
while(m--){
scanf("%d%d",&x,&y);
int fx=find(x),fy=find(y);
if(fx==fy)
puts("-1");
else{
int a=root[fx],b=root[fy];
heap[a].val>>=1,heap[b].val>>=1;
int A=merge(a,pop(a));
int B=merge(b,pop(b));
fa[fx]=fy;root[fy]=merge(A,B);
printf("%d\n",heap[root[fy]].val);
}
}
}
return 0;
}


by >_< NeighThorn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: