[ACM] [BST] Luogu 5076 ordinary binary tree (simplified version)

topic

Insert picture description here

Ideas:

There is nothing to say, but naked BST.
Do the binary tree problem for the first time, record it for later review.
It should be noted that when the predecessor is not found, the output is negative infinity, and when the successor is not found, the output is positive infinity ... Looking for the number according to the ranking, the positive output is not found.
In addition, two of the big guys in the Luogu problem solving area are wrong. The test sample is correct, and they understand it wrong. (The ranking is the number of numbers that are smaller than this number plus 1, the 3 in the example Not ranked second). Maybe the test data is not enough, they are all A ...

Code:

#include<bits/stdc++.h>
using namespace std;
const int inf=0x7fffffff;
//BST
int cont=0,ans;
struct node{
	int ls,rs,val,siz,cnt;
}tree[500004];
//x 现在的节点 y 值 
void insert(int x,int y){
	tree[x].siz++;
	if(tree[x].val==y){
		tree[x].cnt++;
		return;
	}
	if(tree[x].val>y){
		if(tree[x].ls!=0)
			insert(tree[x].ls,y);
		else{
			cont++;
			tree[x].ls=cont;
			tree[cont].cnt=tree[cont].siz=1;
			tree[cont].val=y;
		}
	}
	else{
		if(tree[x].rs!=0)
			insert(tree[x].rs,y);
		else{
			cont++;
			tree[x].rs=cont;
			tree[cont].cnt=tree[cont].siz=1;
			tree[cont].val=y;
		}
	}
}
//x 现在的节点 val 值 
int search(int x,int val){
	if(x==0) return 0;
	if(val==tree[x].val)return tree[tree[x].ls].siz;
	if(val>tree[x].val)return tree[tree[x].ls].siz+tree[x].cnt+search(tree[x].rs,val);
	if(val<tree[x].val)return search(tree[x].ls,val);
}
//y排名 
int search2(int x,int y){
	if(x==0) return inf;
	if(tree[tree[x].ls].siz>=y)return search2(tree[x].ls,y);
	if(tree[tree[x].ls].siz+tree[x].cnt>=y)return tree[x].val;
	if(y>tree[tree[x].ls].siz)return search2(tree[x].rs,y-tree[tree[x].ls].siz-tree[x].cnt);
}
//找前驱
void searchf(int x,int val){
	if(x==0) return;
	if(tree[x].val<val){
		ans=max(ans,tree[x].val);
		searchf(tree[x].rs,val);
	}
	if(tree[x].val>=val){
		searchf(tree[x].ls,val);
	}
}
//找后继
void searchl(int x,int val){
	if(x==0) return;
	if(tree[x].val>val){
		ans=min(ans,tree[x].val);
		searchl(tree[x].ls,val);
	}
	if(tree[x].val<=val){
		searchl(tree[x].rs,val);
	}
}
int main(){
	int n;
	int type,num;
	scanf("%d",&n);
	while(n--){
		scanf("%d %d",&type,&num);
		if(type==5){
			if(cont==0){
				cont++;
				tree[1].cnt=tree[1].siz=1;
				tree[1].val=num;
			}
			else insert(1,num);
		}
		if(type==1)printf("%d\n",search(1,num)+1);//查找排名 
		if(type==2)printf("%d\n",search2(1,num));//依据排名查找数字 
		if(type==3)ans=-inf,searchf(1,num),printf("%d\n",ans);//查找前驱 
		if(type==4)ans=inf,searchl(1,num),printf("%d\n",ans);//查找后继 
	}
}
Published 9 original articles · won 0 · 99 visits

Guess you like

Origin blog.csdn.net/weixin_45497996/article/details/105448674