HDU 1512 Monkey King 并查集+左偏树

5 篇文章 0 订阅

时空隧道


代码如下:

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值