【非旋Treap的近親?!】左偏樹[數組版]

本文介绍了一种高效的数据结构——左偏树,并通过对比非旋Treap来阐述其特点。针对删除操作使用数组实现的方式进行了讨论,特别说明了在洛谷模板题中为何采用此方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

左偏樹

話説左偏樹和非旋Treap好像好像的呢
沒什麽可説
至於爲什麽用數組寫
是因爲luogu模板題要求刪除最前面那個數用指針寫起來麻煩

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cctype>
#define MAXN 100010
using namespace std;
inline void read(int &x)
{
    int s=0,w=1;
    char c=getchar();
    while(!isdigit(c)){if(c=='-')w=-1;c=getchar();}
    while(isdigit(c)){s=(s<<3)+(s<<1)+c-'0';c=getchar();}
    x=s*w;
}
inline void write(int x)
{
    if(x<0)putchar('-'),x=-x;
    if(x>9)write(x/10);
    putchar(x%10+'0');
}
struct node
{
    int key,dis,ls,rs,fa;
}t[MAXN];
inline void push_up(int x)
{
    t[x].dis=t[t[x].rs].dis+1;
}
int merge(int x,int y)
{
    if(!x||!y)return x+y;
    if(t[x].key>t[y].key||t[x].key==t[y].key&&x>y)
        swap(x,y);
    t[x].rs=merge(t[x].rs,y);
    t[t[x].rs].fa=x;
    if(t[t[x].rs].dis>t[t[x].ls].dis)
        swap(t[x].ls,t[x].rs);
    push_up(x);
    return x;
}
inline int find(int x)
{
    while(t[x].fa)
        x=t[x].fa;
    return x;
}
inline void pop(int x)
{
    t[x].key=-1;
    t[t[x].ls].fa=t[t[x].rs].fa=0;
    merge(t[x].ls,t[x].rs);
}
int n,m,opt,x,y;
int main()
{
    read(n),read(m);
    for(int i=1;i<=n;i++)read(t[i].key);
    while(m--)
    {
        read(opt);
        if(opt==1)
        {
            read(x),read(y);
            int a=find(x),b=find(y);
            if(t[a].key==-1||t[b].key==-1||a==b)continue;
            merge(a,b);
        }
        else
        {
            read(x);
            if(t[x].key==-1)puts("-1");
            else
            {
                y=find(x);
                write(t[y].key),putchar(10);
                pop(y);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值