蒟蒻刚学Splay 求问为什么加上注释的地方会超市
查看原帖
蒟蒻刚学Splay 求问为什么加上注释的地方会超市
965007
SMXChina楼主2025/7/25 17:03
#include<bits/stdc++.h>
using namespace std;

const int N=1e5+10;

int n,rt,tot,siz[N],cnt[N],val[N],son[N][2],fa[N];

void pushup(int x)
{
	siz[x]=siz[son[x][0]]+siz[son[x][1]]+cnt[x];
	return ;
}

int getopt(int x)
{
	return son[fa[x]][1]==x;
}

void cle(int x)
{
	son[x][0]=son[x][1]=cnt[x]=val[x]=siz[x]=0;
	son[fa[x]][getopt(x)]=0;//here
	return ;
}

void rotate(int x)
{
	int y=fa[x],z=fa[y],opt=getopt(x);
	son[y][opt]=son[x][opt^1];
	fa[son[y][opt]]=y;
	son[x][opt^1]=y;
	fa[x]=z;
	if(z)
	{
		son[z][getopt(y)]=x;
	}
	fa[y]=x;
	pushup(x);
	pushup(y);
	return ;
}

void splay(int x)
{
	for(int f;f=fa[x];rotate(x))
	{
		if(fa[f])
		{
			if(getopt(x)==getopt(f))
			{
				rotate(f);
			}
			else
			{
				rotate(x);
			}
		}
	}
	rt=x;
	return ;
}

void insert(int x)
{
	if(!rt)
	{
		rt=++tot;
		siz[tot]=cnt[tot]=1;
		val[tot]=x;
		return ;
	}
	int now=rt,f=0;
	while(1)
	{
		if(val[now]==x)
		{
			cnt[now]++;
			pushup(now);
			pushup(f);
			splay(now);
			break;
		}
		f=now;
		now=son[now][x>val[now]];
		if(!now)
		{
			fa[++tot]=f;
			siz[tot]=cnt[tot]=1;
			son[f][x>val[f]]=tot;
			val[tot]=x;
			pushup(f);
			splay(tot);
			break;
		}
	}
	return ;
}

int kth(int k)
{
	int now=rt;
	while(1)
	{
		if(k<=siz[son[now][0]]) now=son[now][0];
		else
		{
			int tmp=siz[son[now][0]]+cnt[now];
			if(k<=tmp) return val[now];
			k-=tmp;
			now=son[now][1];
		}
	}
}

int askrank(int k)
{
	int now=rt,res=0;
	while(now)
	{
		if(k<val[now]) now=son[now][0];
		else
		{
			res+=siz[son[now][0]];
			if(k==val[now])
			{
				splay(now);
				return res+1;
			}
			res+=cnt[now];
			now=son[now][1];
		}
	}
	return res+1;
}

int pre(int k)
{
	int now=son[rt][0];
	while(son[now][1]) now=son[now][1];
	return now;
}

int nxt(int k)
{
	int now=son[rt][1];
	while(son[now][0]) now=son[now][0];
	return now;
}

void del(int x)
{
	int rk=askrank(x);
	if(cnt[rt]>1)
	{
		cnt[rt]--;
		pushup(rt);
		return ;
	}
	if(!son[rt][0]&&!son[rt][1])
	{
		cle(rt);
		rt=0;
		return ;
	}
	if(!son[rt][0])
	{
		int oldrt=rt;
		rt=son[rt][1];
		fa[rt]=0;
		cle(oldrt);
		return ;
	}
	if(!son[rt][1])
	{
		int oldrt=rt;
		rt=son[rt][0];
		fa[rt]=0;
		cle(oldrt);
		return ;
	}
	int mx=pre(x),oldrt=rt;
	splay(mx);
	son[rt][1]=son[oldrt][1];
	fa[son[oldrt][1]]=rt;
	cle(oldrt);
	pushup(rt);
	return ;
}

int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		int opt,x;
		cin>>opt>>x;
		if(opt==1)
		{
			insert(x);
		}
		else if(opt==2)
		{
			del(x);
		}
		else if(opt==3)
		{
			cout<<askrank(x)<<endl;
		}
		else if(opt==4)
		{
			cout<<kth(x)<<endl;
		}
		else if(opt==5)
		{
			insert(x);
			cout<<val[pre(x)]<<endl;
			del(x);
		}
		else
		{
			insert(x);
			cout<<val[nxt(x)]<<endl;
			del(x);
		}
	}
	return 0;
}
2025/7/25 17:03
加载中...