LuoguP1456 Monkey King (左偏树)

struct LeftTree{
    int l,r,val,dis;
}t[N];
int fa[N];
inline int Find(int x){
    return x == fa[x] ? x : fa[x] = Find(fa[x]);
}
inline int Merge(int x, int y){
    if(!x) return y;
    if(!y) return x;
    if(t[x].val < t[y].val || (t[x].val == t[y].val && x > y)) Swap(x, y);
    t[x].r = Merge(t[x].r, y);
    fa[t[x].r] = fa[t[x].l] = x;
    if(t[t[x].r].dis > t[t[x].l].dis) Swap(t[x].r, t[x].l);
    t[x].dis = t[t[x].r].dis + 1;
    return x;
}

int main(){
    int n,m;
    while(~scanf("%d", &n)){
        
        R(i,1,n){
            t[i].l = t[i].r = t[i].dis = 0;
            io >> t[i].val;
            fa[i] = i;
        }
        
        io >> m;
        
        while(m--){
            int x,y;
            io >> x >> y;
            x = Find(x), y = Find(y);
            if(x == y){
                printf("-1\n"); continue;
            }
            
            t[x].val >>= 1;
            int rt = Merge(t[x].l, t[x].r); // the left and right united and elected the new king
            t[x].l = t[x].r = 0; // the old king lost everything
            x = Merge(x, rt); // the fight between the old and the new, only the winner was deserved to be king
            
            t[y].val >>= 1;
            rt = Merge(t[y].l, t[y].r);
            t[y].l = t[y].r = 0;
            y = Merge(y, rt);
            
            rt = Merge(x, y); // the winner of the two groups
            fa[x] = fa[y] = rt; // ought to  rule the union
            
            printf("%d\n", t[rt].val);
        }
        
    }
    
    return 0;
}

转载于:https://www.cnblogs.com/bingoyes/p/11186011.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值