题目
这是原创。。。不知道为什么一直说是转载 不让通过。。。mmp
#include<cstdio>
#include<iostream>
#include<cstring>
#define en '\n'
#define m(a,b) memset(a,b,sizeof a)
using namespace std;
typedef long long ll;
const int N=1e5+5;
int val[N],f[N],ls[N],rs[N],dis[N];
int seek(int x){
return (x==f[x])?(x):(f[x]=seek(f[x]));
}
int combine(int x,int y){
if(!x||!y) return x+y;
if(val[x]<val[y]) swap(x,y);
rs[x]=combine(rs[x],y);
if(dis[ls[x]]<dis[rs[x]]) swap(ls[x],rs[x]);//改成我原来的板子就T了。。
dis[x]=dis[rs[x]]+1;
return x;
}
int pop(int x){
val[x]/=2;
f[x]=combine(ls[x],rs[x]),f[f[x]]=f[x];
ls[x]=rs[x]=dis[x]=0;//x还可用到 注意清零。。一定!!!
return f[x];
}
int main(){
int n,m;
while(~scanf("%d",&n)){
m(ls,0),m(rs,0),m(dis,0);
for(int i=1;i<=n;++i) scanf("%d",&val[i]),f[i]=i;
int m;scanf("%d",&m);
while(m--){
int x,y;scanf("%d%d",&x,&y);
int rx=seek(x),ry=seek(y);
if(rx==ry) {puts("-1");continue;}
int top,topx,topy;//将新根top与rx合并。
top=pop(rx),topx=combine(top,rx),f[top]=f[rx]=topx;
top=pop(ry),topy=combine(top,ry),f[top]=f[ry]=topy;
top=combine(topx,topy),f[topx]=f[topy]=top;//合并两个堆
printf("%d\n",val[top]);
}
}
}