左偏树入门题,模板题。
照板打就行了,左偏树的删除、插入都可以通过merge操作完成。
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100005;
struct tree {
int l,r,v,dis,f;
}heap[maxn];
int merge(int a,int b) {
if(a==0)return b;
if(b==0)return a;
if(heap[a].v<heap[b].v)swap(a,b);
heap[a].r=merge(heap[a].r,b);
heap[heap[a].r].f=a;
if(heap[heap[a].l].dis<heap[heap[a].r].dis)swap(heap[a].l,heap[a].r);
if(heap[a].r==0)heap[a].dis=0;
else heap[a].dis=heap[heap[a].r].dis+1;
return a;
}
int pop( int a ) {
int l=heap[a].l,r=heap[a].r;
heap[l].f=l;
heap[r].f=r;
heap[a].l=heap[a].r=heap[a].dis=0;
return merge(l,r);
}
int find( int a ){return heap[a].f==a?a:find(heap[a].f);}
template<class T>inline void read(T &res){
static char ch;T flag=1;
while((ch=getchar())<'0'||ch>'9')if(ch=='-')flag=-1;res=ch-48;
while((ch=getchar())>='0'&&ch<='9')res=(res<<1)+(res<<3)+ch-48;res*=flag;
}
int main() {
int a,b,finda,findb,n,m;
while(scanf("%d",&n)!=EOF) {
for(register int i=1;i<=n;++i ) {
read(heap[i].v);
heap[i].l=heap[i].r=heap[i].dis=0;
heap[i].f=i;
}
read(m);
while(m--){
read(a),read(b);
finda=find(a);
findb=find(b);
if(finda==findb) {
printf("-1\n");
}else{
heap[finda].v>>=1;
int u=pop( finda );
u=merge(u,finda );
heap[findb].v>>=1;
int v=pop(findb);
v=merge(v,findb);
printf("%d\n",heap[merge(u,v)].v);
}
}
}
return 0;
}