HDU 1512 Monkey King [可并堆]

3 篇文章 0 订阅
1 篇文章 0 订阅

题目传送门

左偏树入门题,模板题。
照板打就行了,左偏树的删除、插入都可以通过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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值