AVL20pts求助,悬赏1关注
查看原帖
AVL20pts求助,悬赏1关注
501947
DengDuck鄧德楼主2023/1/10 20:45
#include<bits/stdc++.h>
using namespace std;
long long n,op,x,tot,rt;
struct node
{
    long long ch[2],val,h,sz;
}t[1000005];
void pushup(long long rt)
{
    if(rt)
    {
        t[rt].sz=t[t[rt].ch[0]].sz+t[t[rt].ch[1]].sz+1;
        t[rt].h=max(t[t[rt].ch[0]].h,t[t[rt].ch[1]].h)+1;
    }
}
void zig(long long &rt)
{
    long long k=t[rt].ch[0];
    t[rt].ch[0]=t[k].ch[1],t[k].ch[1]=rt,pushup(k),pushup(rt),rt=k;
}
void zag(long long &rt)
{
    long long k=t[rt].ch[1];
    t[rt].ch[1]=t[k].ch[0],t[k].ch[0]=rt,pushup(k),pushup(rt),rt=k;
}
void zigzag(long long &rt)
{
    zag(t[rt].ch[0]);
    zig(rt);
}
void zagzig(long long &rt)
{
    zig(t[rt].ch[1]);
    zag(rt);
}
void maintain(long long &rt)
{
    if(t[t[rt].ch[0]].h+2<=t[t[rt].ch[1]].h)
    {
        if(t[t[t[rt].ch[1]].ch[1]].h<t[t[t[rt].ch[1]].ch[0]].h)zigzag(rt);
        else zag(rt);
    }
    else if(t[t[rt].ch[1]].h+2<=t[t[rt].ch[0]].h)
    {
        if(t[t[t[rt].ch[0]].ch[1]].h<t[t[t[rt].ch[0]].ch[0]].h)zig(rt);
        else zagzig(rt);
    }
    pushup(rt);
}
void ins(long long &rt,long long x)
{
    if(rt==0)
    {
        rt=++tot;
        t[rt].val=x;
        pushup(rt);
        return;
    }
    ins(t[rt].ch[x>t[rt].val],x);
    pushup(rt);
    maintain(rt);
}
void del(long long &rt,long long x)
{
    if(rt==0)return;
    if(t[rt].val==x)
    {
        if(t[rt].ch[0]==0||t[rt].ch[1]==0)rt=t[rt].ch[0]+t[rt].ch[1];
        else zig(x),del(t[rt].ch[1],x);
    }
    else del(t[rt].ch[x>t[rt].val],x);
    pushup(rt);
    maintain(rt);
}
long long kth(long long &rt,long long x)
{
    if(rt==0)return -1;
    if(x<=t[t[rt].ch[0]].sz)return kth(t[rt].ch[0],x);
    if(x==t[t[rt].ch[0]].sz+1)return t[rt].val;
    return kth(t[rt].ch[1],x-t[t[rt].ch[0]].sz-1);
}
long long rk(long long &rt,long long x)
{
    if(rt==0)return 1;
    if(x<=t[rt].val)return rk(t[rt].ch[0],x);
    return rk(t[rt].ch[1],x)+t[t[rt].ch[0]].sz+1;
}
int main()
{
    scanf("%lld",&n);
    while(n--)
    {
        scanf("%lld%lld",&op,&x);
        if(op==1)ins(rt,x);
        if(op==2)del(rt,x);
        if(op==3)printf("%lld\n",rk(rt,x));
        if(op==4)printf("%lld\n",kth(rt,x));
        if(op==5)printf("%lld\n",kth(rt,rk(rt,x)-1));
        if(op==6)printf("%lld\n",kth(rt,rk(rt,x+1)));
       // cout<<rt<<' '<<t[rt].val<<' '<<t[rt].h<<' '<<t[rt].sz<<endl;
    }
}
2023/1/10 20:45
加载中...