Monkey King-左偏树
题目描述
题解
可并堆,左偏树
注意:重新合并时,把根的信息清空
代码实现
#include<bits/stdc++.h>
#define M 100009
using namespace std;
int n,m,f[M],a[M],root[M],dis[M],ch[M][2],s;
bool die[M];
int getfa(int x){
if(f[x]==x) return x;
else return f[x]=getfa(f[x]);
}
int merge(int x,int y){
if(!x||!y) return x+y;
if(a[x]<a[y]) swap(x,y);
ch[x][1]=merge(ch[x][1],y);
if(dis[ch[x][0]]<dis[ch[x][1]])
swap(ch[x][0],ch[x][1]);
dis[x]=dis[ch[x][1]]+1;
return x;
}
int main(){
int x,y;
while(~scanf("%d",&n)){
memset(ch,0,sizeof(ch));
memset(dis,0,sizeof(dis));
dis[0]=-1;
for(int i=1;i<=n;i++) f[i]=root[i]=i;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
for(int i=1;i<=m;i++){
scanf("%d%d",&x,&y);
int fx=getfa(x),fy=getfa(y);
if(fx==fy) printf("-1\n");
else{
int r=root[fx],w=root[fy];
a[r]>>=1,a[w]>>=1;
f[fx]=fy;
root[fy]=merge(ch[w][0],ch[w][1]);
ch[w][0]=ch[w][1]=dis[w]=0;
root[fy]=merge(root[fy],w);
root[fx]=merge(ch[r][0],ch[r][1]);
ch[r][0]=ch[r][1]=dis[r]=0;
root[fx]=merge(root[fx],r);
root[fy]=merge(root[fx],root[fy]);
printf("%d\n",a[root[fy]]);
}
}
}return 0;
}