首页 > 其他 > 详细

splay

时间:2019-09-29 17:17:51      阅读:77      评论:0      收藏:0      [点我收藏+]

  

P3369 【模板】普通平衡树

技术分享图片

 

技术分享图片
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i>=(b);--i)
#define ll long long
#define see(x) (cerr<<(#x)<<‘=‘<<(x)<<endl)
#define inf 0x3f3f3f3f
#define CLR(A,v)  memset(A,v,sizeof A)
//////////////////////////////////
const int N=2e6+10;
int son[N][2],fa[N],siz[N],cnt[N],val[N],ncnt,root;

int chk(int x){return son[fa[x]][1]==x;}
void up(int x){siz[x]=siz[son[x][0]]+siz[son[x][1]]+cnt[x];}
void rotate(int x)
{
    int y=fa[x],z=fa[y],k=chk(x),w=son[x][k^1];
    son[y][k]=w;fa[w]=y;
    son[z][chk(y)]=x;fa[x]=z;
    son[x][k^1]=y;fa[y]=x;
    up(y);up(x);
}
void splay(int x,int goal=0)
{
    while(fa[x]!=goal)
    {
        int y=fa[x],z=fa[y];
        if(z!=goal)
        {
            if(chk(y)==chk(z))rotate(y);
            else rotate(x);
        }
        rotate(x);
    }
    if(!goal)root=x;
}
void find(int x)
{
    if(!root)return ;
    int pos=root;
    while(son[pos][x>val[pos]]&&val[pos]!=x)pos=son[pos][x>val[pos]];
    splay(pos);
}
void insert(int x)
{
    int pos=root,p=0;
    while(pos&&val[pos]!=x)p=pos,pos=son[pos][x>val[pos]];
    if(pos)cnt[pos]++;
    else 
    {   
        pos=++ncnt;
        son[pos][0]=son[pos][1]=0;
        if(p)fa[pos]=p,son[p][x>val[p]]=pos;
        siz[pos]=cnt[pos]=1;
        val[pos]=x;
    }
    splay(pos);
}
int kth(int k)
{
    int pos=root;
    while(1)
    {
        if(son[pos][0]&&siz[son[pos][0]]>=k)pos=son[pos][0];
        else if(siz[son[pos][0]]+cnt[pos]<k)k-=siz[son[pos][0]]+cnt[pos],pos=son[pos][1];
        else {splay(pos);return pos;}
    }
}
int nex(int x,int flag)
{
    find(x);
    int pos=root;
    if(!flag&&val[pos]<x)return pos;
    if(flag&&val[pos]>x)return pos;
    pos=son[pos][flag];
    while(son[pos][flag^1])pos=son[pos][flag^1];
    splay(pos);return pos;
}
void remove(int x)
{
    int last=nex(x,0),nexx=nex(x,1);
    splay(last),splay(nexx,last);
    int pos=son[nexx][0];
    if(cnt[pos]>1)cnt[pos]--,splay(pos);
    else son[nexx][0]=0;
    up(nexx);up(root);
}
void rank1(int x)
{
    find(x);
    if(val[root]<=x)printf("%d\n",siz[son[root][0]]);
    else printf("%d\n",siz[son[root][0]]+cnt[root]);
}

int main()
{
    int m;cin>>m; int a,b;
    insert(0x3f3f3f3f);
    insert(0xcfcfcfcf);
    while(m--)
    {
       scanf("%d%d",&a,&b);
        if(a==1)insert(b);
        if(a==2)remove(b);
        if(a==3)rank1(b);
        if(a==4)printf("%d\n", val[kth(b+1)] );
        if(a==5)printf("%d\n",val[nex(b,0)]);
        if(a==6)printf("%d\n",val[nex(b,1)]);
    }
    return 0;
}
View Code

 

splay

原文:https://www.cnblogs.com/bxd123/p/11608926.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!