求调Treap
查看原帖
求调Treap
233462
Umbrella_Leaf楼主2021/3/24 15:40
#include<bits/stdc++.h>
using namespace std;
namespace Treap{
	struct node{
		int value,cnt,size;
		int rd;
		node* son[2];
		node(int value):value(value){
			son[0]=son[1]=NULL;rd=rand();cnt=size=1;
		}
		bool operator <(const node& rhs)const{
			return rd<rhs.rd;
		}
	};
	int num;
	node* Root;
	void init(){
		Root=NULL;
	}
	void pushup(node* p){
		p->size=p->cnt;
		if(p->son[0]!=NULL)p->size+=p->son[0]->size;
		if(p->son[1]!=NULL)p->size+=p->son[1]->size;
	}
	void rotate(node* &p,int d){
		node* k=p->son[d^1];
		p->son[d^1]=k->son[d];
		k->son[d]=p;
		pushup(p);
		pushup(k);
		p=k;
	}
	void insert(node* &p,int x){
		if(p==NULL){
			p=new node(x);
		}else if(x==p->value){
			p->cnt++;
		}else{
			int d=(x<p->value?0:1);
			insert(p->son[d],x);
			if(p->son[d]->rd>p->rd)rotate(p,d^1);
		}
		pushup(p);
	}
	void remove(node* &p,int x){
		if(p->value==x){
			node* u=p;
			if(p->son[0]!=NULL&&p->son[1]!=NULL){
				int d2=(p->son[0]->rd>p->son[1]->rd?1:0);
				rotate(p,d2);
				remove(p->son[d2],x);
			}else{
				if(p->son[0]==NULL)p=p->son[1];
				else p=p->son[0];
				if(u->cnt==1)delete u;
				else u->cnt--;
			}
		}else{
			int d=(x<p->value?0:1);
			remove(p->son[d],x);
		}
		if(p!=NULL)pushup(p);
	}
	int rank(node* p,int x){
		if(p==NULL)return 0;
		int s=(p->son[0]==NULL?0:p->son[0]->size);
		if(p->value==x)return s+1;
		else if(p->value>x)return rank(p->son[0],x);
		else return rank(p->son[1],x)+s+p->cnt;
	}
	int kth(node* p,int k){
		if(p==NULL||k<=0||k>p->size)return 0;
		int s=(p->son[0]==NULL?0:p->son[0]->size);
		if(k<=s)return kth(p->son[0],k);
		else if(k<=s+p->cnt)return p->value;
		else return kth(p->son[1],k-s-p->cnt);
	}
	int pre(node* p,int x){
		if(p==NULL)return -(1<<30);
		if(p->value>=x)return pre(p->son[0],x);
		else return max(pre(p->son[1],x),p->value);
	}
	int suc(node* p,int x){
		if(p==NULL)return 1<<30;
		if(p->value<=x)return suc(p->son[1],x);
		else return min(suc(p->son[0],x),p->value);
	}
}
int main(){
	srand(19620817);
	int q;
	scanf("%d",&q);
	Treap::init();
	while(q--){
		int opt,x;
		scanf("%d%d",&opt,&x);
		if(opt==1)Treap::insert(Treap::Root,x);
		else if(opt==2)Treap::remove(Treap::Root,x);
		else if(opt==3)printf("%d\n",Treap::rank(Treap::Root,x));
		else if(opt==4)printf("%d\n",Treap::kth(Treap::Root,x));
		else if(opt==5)printf("%d\n",Treap::pre(Treap::Root,x));
		else if(opt==6)printf("%d\n",Treap::suc(Treap::Root,x));
	}
	return 0;
}

这样有什么错误么?#6 WA,#7~10 RE

2021/3/24 15:40
加载中...