P3377 【模板】左偏树(可并堆)

[题目链接] https://www.luogu.org/problemnew/show/P3377

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF=1e9+7;
inline LL read(){
    register LL x=0,f=1;register char c=getchar();
    while(c<48||c>57){if(c=='-')f=-1;c=getchar();}
    while(c>=48&&c<=57)x=(x<<3)+(x<<1)+(c&15),c=getchar();
    return f*x;
}

const int MAXN=1e5+5;

struct Tree{
    int val,ls,rs,rt,dis;
}a[MAXN];

int n,m;

inline int Getrt(int x){return x==a[x].rt?x:a[x].rt=Getrt(a[x].rt);}

inline int Merge(int x,int y){
    if(!x||!y) return x+y;
    if(a[x].val>a[y].val||(a[x].val==a[y].val&&x>y)) swap(x,y);
    a[x].rs=Merge(a[x].rs,y);
    if(a[a[x].ls].dis<a[a[x].rs].dis) swap(a[x].ls,a[x].rs);
    a[x].rt=a[a[x].ls].rt=a[a[x].rs].rt=x;
    a[x].dis=a[a[x].rs].dis+1;
    return x;
}

inline void Pop(int x){
    a[x].val=-1;
    //a[a[x].ls].rt=a[a[x].rs].rt=Merge(a[x].ls,a[x].rs);
    a[a[x].ls].rt=a[x].ls,a[a[x].rs].rt=a[x].rs;
    a[x].rt=Merge(a[x].ls,a[x].rs);
}

int main(){
    n=read(),m=read();
    a[0].dis=-1;
    for(int i=1;i<=n;i++)
        a[i].val=read(),a[i].rt=i,a[i].ls=a[i].rs=0;
    for(int i=1;i<=m;i++){
        int op=read();
        if(op==1){
            int x=read(),y=read();
            if(a[x].val==-1||a[y].val==-1) continue;
            int fx=Getrt(x),fy=Getrt(y);
            if(fx!=fy) a[fx].rt=a[fy].rt=Merge(fx,fy);
        }
        if(op==2){
            int x=read(),fx=Getrt(x);
            if(a[x].val==-1){
                printf("%d\n",-1);
                continue;
            }
            printf("%d\n",a[fx].val);
            Pop(fx);
        }
    }
}

[数据加强版] https://www.luogu.org/problemnew/show/P2713

[代码] https://www.luogu.org/recordnew/show/16436151

转载于:https://www.cnblogs.com/lizehon/p/10392260.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值