题解 P3369 【模板】普通平衡树

luogu

#include<bits/stdc++.h>
using namespace std;
int son[1000010][2],val[1000010],cnt[1000010],Fa[1000010],size[1000010];
int root,ncnt;
int n,pd,num;
int Check(int x)
{
	return son[Fa[x]][1]==x;
}
int pushup(int x)
{
    size[x]=size[son[x][0]]+size[son[x][1]]+cnt[x];
}
int rotate(int x)
{
	int y=Fa[x],z=Fa[y],chk=Check(x),tmp=son[x][!chk];
	son[y][chk]=tmp;
	Fa[tmp]=y;
	son[z][Check(y)]=x;
	Fa[x]=z;
	son[x][!chk]=y;
	Fa[y]=x;
	pushup(x);
	pushup(y);
}
int Splay(int x,int goal=0)
{
	for(;Fa[x]!=goal;)
	{
		int y=Fa[x],z=Fa[y];
		if(z!=goal)
		{
			if(Check(x)==Check(y))
			{
				rotate(y);
			}
			else
			{
				rotate(x);
			}
		}
		rotate(x);
	}
	if(!goal)
	{
		root=x;
	}
}
int Find(int x)
{
	if(!root)
	{
		return 0;
	}
	int Res=root;
	for(;son[Res][x>val[Res]]&&x!=val[Res];)
	{
		Res=son[Res][x>val[Res]];
	}
	Splay(Res);
}
int insert(int x)
{
	int Res=root,p=0;
	for(;Res&&val[Res]!=x;)
	{
        p=Res;
        Res=son[Res][x>val[Res]];
    }
    if(Res)
    {
    	cnt[Res]++;
    }
    else
    {
    	Res=++ncnt;
        if(p)
        {
        	son[p][x>val[p]]=Res;
        }
        son[Res][0]=0;
		son[Res][1]=0;
        val[Res]=x;
		Fa[Res]=p;
        cnt[Res]=1;
		size[Res]=1;
    }
    Splay(Res);
}
int xth(int x)
{
	int Res=root;
	for(;;)
	{
		if(x<=size[son[Res][0]]&&son[Res][0])
		{
			Res=son[Res][0];
		}
		else
		{
			if(x>size[son[Res][0]]+cnt[Res])
			{
				x-=size[son[Res][0]]+cnt[Res];
				Res=son[Res][1];
			}
			else
			{
				return Res;
			}
		}
	}
}
int RANK(int x)
{
	Find(x);
	return size[son[root][0]];
}
int Pre(int x)
{
	Find(x);
	if(val[root]<x)
	{
		return root;
	}
	int Res=son[root][0]; 
	for(;son[Res][1];)
	{
		Res=son[Res][1];
	}
	return Res;
}
int Suc(int x)
{
	Find(x);
	if(val[root]>x)
	{
		return root;
	}
	int Res=son[root][1]; 
	for(;son[Res][0];)
	{
		Res=son[Res][0];
	}
	return Res;
}
int Delete(int x)
{
	int las=Pre(x),nex=Suc(x);
	Splay(las);
	Splay(nex,las);
	int DEL=son[nex][0];
	if(cnt[DEL]>1)
	{
        cnt[DEL]--;
        Splay(DEL);
    }
    else
	{
		son[nex][0]=0;
	} 
}
int main()
{
	cin>>n;
	insert(-1000000000);
	insert(1000000000);
	for(int i=1;i<=n;i++)
	{
		cin>>pd>>num;
		if(pd==1)
		{
			 insert(num); 
		}
		if(pd==2)
		{
			 Delete(num);
		}
		if(pd==3)
		{
			 cout<<RANK(num)<<endl;
		}
		if(pd==4)
		{
			 cout<<val[xth(num+1)]<<endl;
		}
		if(pd==5)
		{
			 cout<<val[Pre(num)]<<endl;
		}
		if(pd==6)
		{
			 cout<<val[Suc(num)]<<endl;
		}
	}
}
posted @ 2019-03-15 20:42  G_A_TS  阅读(470)  评论(0编辑  收藏  举报