全WA求助
查看原帖
全WA求助
712533
__hqt__楼主2023/11/22 18:52

题目:P5076
数据结构:二叉搜索树
代码:

#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
struct node
{
	int val,l,r,cnt,len;
}a[10001];
int size=0;
int find1(int x,int i)
{
	if(!i)
		return 0;
	if(a[i].val==x)
	{
		return a[a[i].l].len+1;
	}
	else if(a[i].val>x)
	{
		return find1(x,a[i].l);
	}
	else if(a[i].val<x)
	{
		return find1(x,a[i].r)+a[a[i].l].len+a[i].cnt;
	}
}
int find2(int x,int i)
{
	if(!i)
		return 0;
	if(a[a[i].l].len>=x)
	{
		return find2(x,a[i].l);
	}
	if(x<=a[a[i].l].len+a[i].cnt)
	{
		return a[i].val;
	}
	return find2(x-a[i].cnt-a[a[i].l].len,a[i].r);
}
void insert(int x,int i)
{
	if(x<a[i].val)
	{
		if(a[i].l==0)
		{
			a[i].l=++size;
			a[a[i].l].val=x;
			a[a[i].l].cnt++;
			a[a[i].l].l=0;
			a[a[i].l].r=0;
		}
		else
		{
			insert(x,a[i].l);
		}
	}
	else if(x>a[i].val)
	{
		if(a[i].r==0)
		{
			a[i].r=++size;
			a[a[i].r].val=x;
			a[a[i].r].cnt++;
			a[a[i].r].l=0;
			a[a[i].r].r=0;
		}
		else
		{
			insert(x,a[i].r);
		}
	}
	else
	{
		a[i].cnt++;
	}
	a[i].len=a[a[i].l].len+a[a[i].r].len+a[i].cnt;
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int q,op,x;
	cin>>q;
	for(int i=1;i<=q;i++)
	{
		cin>>op>>x;
		if(op==1)
		{
			cout<<find1(x,1)<<endl;
		}
		else if(op==2)
		{
			cout<<find2(x,1)<<endl;
		}
		else if(op==3)
		{
			int temp=find2(find1(x,1)-1,1);
			if(temp==0)
			{
				cout<<"−2147483647\n";
			}
			else
			{
				cout<<temp<<endl;
			}
		}
		else if(op==4)
		{
			int temp=find2(find1(x,1)+1,1);
			if(temp==0)
			{
				cout<<"2147483647\n";
			}
			else
			{
				cout<<temp<<endl;
			}
		}
		else if(op==5)
		{
			insert(x,1);
		}
	}
}

谢谢大佬们

2023/11/22 18:52
加载中...