treap求助
查看原帖
treap求助
940678
lhrfc楼主2023/4/15 21:26
#include <bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
class node{
public:
	node *ls,*rs;
	int val,cnt,size,rnd;
	node(int val){
		ls=nullptr,rs=nullptr;
		this->val=val,cnt=1,size=1;
		rnd=rand();
	}
	inline void pushup(){
		size=cnt;
		if(ls) size+=ls->size;
		if(rs) size+=rs->size;
	}
};
node *root;
inline void zuoxuan(node *&o){
	node *ro=o,*r=o->rs;
	o=r,ro->rs=r->ls,o->ls=ro;
}
inline void youxuan(node *&o){
	node *ro=o,*l=o->ls;
	o=l,ro->ls=l->rs,o->rs=ro;
}

void insert(node *&o,int x){
	if(!o) o=new node(x);
	else{
		if(o->val==x) o->cnt++;
		if(x<o->val){
			insert(o->ls,x);
			if(o->ls->rnd<o->rnd) youxuan(o);
		}
		if(x>o->val){
			insert(o->rs,x);
			if(o->rs->rnd<o->rnd) zuoxuan(o);
		}
	}
	o->pushup();	
}
void del(node *&o,int x){
	if(o->val==x){
		if(o->cnt>1) o->cnt--;
		else{
			if(!o->ls&&!o->rs){
				delete o;
				o=nullptr;
				return;
			}
			if(o->ls&&o->rs){
				if(o->ls->rnd>o->rs->rnd) zuoxuan(o);
				else youxuan(o);
				del(o,x);
			}
			if(!o->rs) o=o->ls;
			if(!o->ls) o=o->rs;
		}
	}
	else if(x<o->val){
		del(o->ls,x);
		youxuan(o);
	}
	else{
		del(o->rs,x);
		zuoxuan(o);	
	}
	if(o) o->pushup();
}
int getRankByVal(node *o,int x){
	if(!o) return 0;
	if(o->val==x) return o->ls->size+1;
	if(x<o->val) return getRankByVal(o->ls,x);
	return getRankByVal(o->rs,x)+o->ls->size+o->cnt;
}
int getValByRank(node *o,int rank){
	if(!o) return inf;
	if(o->ls->size>=rank) return getValByRank(o->ls,rank);
	if(o->ls->size+o->cnt>=rank) return o->val;
	return getValByRank(o->rs,rank-o->ls->size-o->cnt);
}
inline int getPre(int x){
	node *p=root;
	int ans=-inf;
	while(p){
		if(p->val>=x) p=p->ls;
		else ans=p->val,p=p->rs;
	}
	if(ans==-inf) return -1;
	return ans;
}
inline int getNext(int x){
	node *p=root;
	int ans=inf;
	while(p){
		if(p->val<=x) p=p->rs;
		else ans=p->val,p=p->ls;
	}
	if(ans==inf) return -1;
	return ans;
}
inline void init(){
	insert(root,inf),insert(root,-inf);
	root->pushup();	
}
int n;
int main(){
	cin>>n;
	while(n--){
		int opt,x;
		cin>>opt>>x;
		switch(opt){
			case 1:
				insert(root,x);
				break;
			case 2:
				del(root,x);
				break;
			case 3:
				cout<<getRankByVal(root,x)<<endl;
				break;
			case 4:
				cout<<getValByRank(root,x)<<endl;
				break;
			case 5:
				cout<<getPre(x)<<endl;
				break;
			case 6:
				cout<<getNext(x)<<endl;
				break;
				
		}
	}
	return 0;
}

似乎1256四个操作都可以成功运行,但是34错了

2023/4/15 21:26
加载中...