49pts求调
查看原帖
49pts求调
1043658
Purple_meteor楼主2024/1/16 13:27
#include<bits/stdc++.h>
using namespace std;
int totp,n,root=1;
bool rf=1;
struct tree
{
	int l,r,key,cnt,size;
}t[1000000];
int get_new(int x)
{
	t[++totp].key=x;
	t[totp].cnt=t[totp].size=1;
	return totp;
}
void insert(int x)
{
	if(rf)
	{
		t[get_new(x)].key=x;
		rf=0;
		return ;
	}
	int f=root,p=root;
	while(x!=t[p].key&&p)
	{
		t[p].size++;
		f=p;
		if(t[p].key>x) p=t[p].l;
		else p=t[p].r;
	}
	if(!p)
	{
		if(t[f].key>x) t[f].l=p=get_new(x);
		else t[f].r=p=get_new(x);
	}
	else 
	{
		t[p].cnt++;
		t[p].size++;
	}
}
int find_l(int x)
{
	int p=root,ans=INT_MIN,ansp=0;
	while(p)
	{
		if(t[p].key>=x) p=t[p].l;
		else
		{
			if(t[p].key>ans)
			{
				ans=t[p].key;
				ansp=p;
			}
			p=t[p].r;
		}
	}
	return ansp;
}
int find_r(int x)
{
	int p=root,ans=INT_MAX,ansp=0;
	while(p)
	{
		if(t[p].key<=x) p=t[p].r;
		else
		{
			if(t[p].key<ans)
			{
				ans=t[p].key;
				ansp=p;
			}
			p=t[p].l;
		}
	}
	return ansp;
}
int find(int x)
{
	int p=root,ans=0;
	while(x!=t[p].key&&p)
	{
		if(t[p].key>x) p=t[p].l;
		else
		{
			ans+=t[t[p].l].size+t[p].cnt;
			p=t[p].r;
		}
	}
	return ans+t[t[p].l].size+1;
}
int search(int x)
{
	int l=0,p=root;
	while(p)
	{
		if(l+t[t[p].l].size<x&&x<=l+t[t[p].l].size+t[p].cnt) return t[p].key;
		if(x<=t[t[p].l].size+l) p=t[p].l;
		else
		{
			l+=t[t[p].l].size+t[p].cnt;
			p=t[p].r;
		}
	}
	return -1;
}
void rotate(int p,int &f,bool k)
{
	if(k&&t[p].l)
	{
		if(p==root) root=t[p].l;
		else
		{
			if(t[f].l==p) t[f].l=t[p].l;
			else t[f].r=t[p].l;
		}
		int x=t[p].l;
		t[p].size-=t[x].size;
		while(t[x].r)
		{
			t[x].size+=t[p].size;
			x=t[x].r;
		}
		t[x].size+=t[p].size;
		t[x].r=p;
		t[p].l=0;
		f=x;
	}
	else if(!k&&t[p].r)
	{
		if(p==root) root=t[p].r;
		else
		{
			if(t[f].r==p) t[f].r=t[p].r;
			else t[f].l=t[p].r;
		}
		int x=t[p].r;
		t[p].size-=t[x].size;
		while(t[x].l)
		{
			t[x].size+=t[p].size;
			x=t[x].l;
		}
		t[x].size+=t[p].size;
		t[x].l=p;
		t[p].r=0;
		f=x;
	}
}
void remove(int x)
{
	int f=root,p=root;
	
	while(p&&t[p].key!=x)
	{
		f=p;
		if(t[p].key>x) p=t[p].l;
		else p=t[p].r;
	}
	rotate(p,f,true);
	rotate(p,f,false);
	f=root,p=root;
	while(p&&t[p].key!=x)
	{
		t[p].size--;
		f=p;
		if(t[p].key>x) p=t[p].l;
		else p=t[p].r;
	}
	if(t[p].cnt>1)
	{
		t[p].cnt--;
		return ;
	} 
	if(t[f].l==p) t[f].l=0;
	else if(t[f].r==p) t[f].r=0;
	t[p].cnt=0;
	t[p].key=0;
	t[p].l=0;
	t[p].r=0;
	t[p].size=0;
}
int main()
{
	cin>>n;
	int N=n;
	while(n--)
	{
		int op,x;
		cin>>op>>x;
		if(op==1) insert(x);
		if(op==2) remove(x);
		if(op==3) cout<<find(x)<<endl;
		if(op==4) cout<<search(x)<<endl;
		if(op==5) cout<<t[find_l(x)].key<<endl;
		if(op==6) cout<<t[find_r(x)].key<<endl;
	}
	return 0;
} 
2024/1/16 13:27
加载中...