左偏树学习笔记

· · 个人记录

左偏树具有类似堆的性质,可以支持快速合并,通常用于维护可并堆。

#include <bits/stdc++.h>
using namespace std;

inline int read()
{
    int x=0; int f=1; char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-')f=-1; ch=getchar();}
    while(isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}

const int MAXN = 100005;
int l[MAXN],r[MAXN],val[MAXN];
int dis[MAXN],fa[MAXN];
int n,m;

inline int merge(int x,int y)
{
    if(!x||!y) return x|y;
    if(val[x]>val[y] || val[x]==val[y] && x>y) swap(x,y);
    r[x]=merge(r[x],y);
    if(dis[l[x]]<dis[r[x]]) swap(l[x],r[x]);
    fa[l[x]]=fa[r[x]]=fa[x]=x;
    dis[x]=dis[r[x]]+1; return x;
}

inline int top(int x)
{
    if(fa[x]==x) return x;
    return fa[x]=top(fa[x]);
}

inline void pop(int x)
{
    fa[l[x]]=l[x]; fa[r[x]]=r[x];
    val[x]=-1; fa[x]=merge(l[x],r[x]);
}

int main(int argc, char const *argv[])
{
    n=read(); m=read(); dis[0]=-1;
    for (int i = 1; i <= n; ++i)
        fa[i]=i,val[i]=read();
    int opt,x,y;
    for (int i = 1; i <= m; ++i)
    {
        opt=read(); x=read();
        if (opt==1)
        {
            y=read();
            if (val[x]==-1 || val[y]==-1) continue;
            if (x==y) continue;
            fa[x]=fa[y]=merge(top(x),top(y));
        }
        if(opt==2)
        {
            if (val[x]==-1) puts("-1");
            else
            {
                y=top(x);
                printf("%d\n",val[top(x)]);
                pop(top(y));
            }
        }
    }
    return 0;
}