为何MLE
查看原帖
为何MLE
186162
齐心协力楼主2021/1/10 16:31
#include<bits/stdc++.h>
using namespace std;
struct mytree{
	int cnt,l,r,val,size;
}t[100010];
int tot;
void ins(int p,int x)
{
	t[p].size++;
	if(t[p].val==x)
	{
		t[p].cnt++;
		return;
	}
	if(x<t[p].val)
	{
		if(t[p].l) ins(t[p].l,x);
		else
		{
			t[++tot].val=x;
			t[p].l=tot;
			t[tot].cnt=1;t[tot].size=1;
		}
	}
	else
	{
		if(t[p].r) ins(t[p].r,x);
		else
		{
			t[++tot].val=x;
			t[p].r=tot;
			t[tot].cnt=1;t[tot].size=1;
		}
	}
}
void mids(int p)
{
	if(p==0) return;
	mids(t[p].l);
	cout<<t[p].val<<" ";
	mids(t[p].r);
}
int getpre(int x)
{
	int ans=-INT_MAX,p=1;
	while(p)
	{
		if(t[p].val==x)
		{
			if(t[p].l)
			{
				p=t[p].l;
				while(t[p].r) p=t[p].r;
				return t[p].val;
			}
			return ans;
		}
		if(t[p].val<x&&t[p].val>ans) ans=t[p].val;
		p=x>t[p].val?t[p].r:t[p].l;
	}
	return ans;
}
int getnext(int x)
{
	int ans=INT_MAX,p=1;
	while(p)
	{
		if(t[p].val==x)
		{
			if(t[p].r)
			{
				p=t[p].r;
				while(t[p].l) p=t[p].l;
				return t[p].val;
			}
			return ans;
		}
		if(t[p].val>x&&t[p].val<ans) ans=t[p].val;
		p=x>t[p].val?t[p].r:t[p].l;
	}
	return ans;
}
void update(int p)
{
	t[p].size=t[t[p].l].size+t[t[p].r].size+t[p].cnt;
}
void del(int p,int x)
{
	if(p==0) return;
	if(t[p].val==x)
	{
		if(t[p].cnt>=2)
		{
			t[p].cnt--;return;
		}
		if(t[p].l==0)
		{
			p=t[p].r;
			update(p);
		}
		if(t[p].r==0)
		{
			p=t[p].l;
			update(p);
		}
		int temp=t[p].r;
		while(t[temp].l) temp=t[temp].l;
		del(t[p].r,t[temp].val);
		t[temp].l=t[p].l;
		t[temp].r=t[p].r;
		p=temp;
		update(p);
	}
	else if(t[p].val<x) del(t[p].r,x);
	else del(t[p].l,x);
}
int getrank(int p,int x)
{
	if(p==0)	return 0;
	if(x==t[p].val)	return t[t[p].l].size;
	if(x<t[p].val)	return getrank(t[p].l,x);
	else	return getrank(t[p].r,x)+t[t[p].l].size+t[p].cnt;
}
int rankval(int p,int x)
{
	if(p==0)	return INT_MAX;
	if(t[t[p].l].size>=x)	return rankval(t[p].l,x);
	if(t[t[p].l].size+t[p].cnt>=x)	return t[p].val;
	return rankval(t[p].r,x-t[t[p].l].size-t[p].cnt);
}
int main()
{
	int n,x,y;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>x>>y;
		if(x==1) ins(1,y);
		if(x==2) del(1,y);
		if(x==3) cout<<getrank(1,y)<<endl;
		if(x==4) cout<<rankval(1,y)<<endl;
		if(x==5) cout<<getpre(y)<<endl;
		if(x==6) cout<<getnext(y)<<endl;
	}
	return 0;
}

新萌刚学BST,求助

2021/1/10 16:31
加载中...