Splay求助
查看原帖
Splay求助
886055
MoonCake2011楼主2023/6/27 18:13
#include<bits/stdc++.h>
using namespace std;
#define null NULL
struct node{
	node *s[2],*fa;
	int val,cnt,siz;
	node(){
		fa=s[0]=s[1]=NULL;
		cnt=siz=0;
	}
};
struct tree{
	node *root;
	bool qson(node *p){
		if(p==NULL) return 0;
		if(p->fa==NULL) return 0;
		return (p==p->fa->s[1]);
	}
	int size(node *p){
		return p==NULL ? 0 :p->siz;
	}
	void update(node *&p){
		p->siz=p->cnt;
		if(p->s[0]!=null) p->siz+=p->s[0]->siz;
		if(p->s[1]!=null) p->siz+=p->s[1]->siz;
	}
	void link(node *fa,node *s,bool d){
    	if(fa!=null) fa->s[d]=s;
    	if(s!=null) s->fa=fa;
	}
	void rotate(node *p){
		node *fa=p->fa,*gfa=fa->fa;
		bool q1=qson(p),q2=qson(fa);
		link(fa,p->s[q1^1],q1);
		link(p,fa,q1^1);
		link(gfa,p,q2);
		update(fa),update(p);
	}
	void splay(node *p,node *fa){
		if(p==null) return;
		while(p->fa!=fa){
			if(p->fa->fa!=fa)
				rotate(qson(p)==qson(p->fa) ? p->fa : p);
			rotate(p);
		}
		if(fa==null) root=p;
	}
	node *find(int x){
		node *p=root;
		if(p==null) return NULL;
		while(x!=p->val && p->s[x>p->val])
			p=p->s[x>p->val]; 
		splay(p,NULL); 
		return p;
	}
	void insert(int x){
		node *p=root,*fa=null;
		while(p!=null && x!=p->val)
			fa=p,p=p->s[p->val<x];
		if(p!=null) p->cnt++;
		else{
			p=new node;
			p->val=x,p->cnt=p->siz=1;
			p->s[0]=p->s[1]=null;
			p->fa=fa;
			if(fa!=null) fa->s[fa->val<x]=p;
		}
		splay(p,null);
	}
	int ranks(int x){
        node *u=pre_find(x);
        if(u) splay(u,NULL);
        return ( u?u->siz-size(u->s[1]) :0 )+1;
    }
    int get(int x){
    	node *p=root;
    	if(p->siz<x) return INT_MAX;
    	while(true){
    		node *u=p->s[0];
    		if(size(u)+p->cnt<x)
    			x-=size(u)+p->cnt,p=p->s[1];
    		else if(x<=size(u)) p=u;
    		else{
    			splay(p,NULL);
    			return p->val;
			}
		}
	}
    node *pre_find(int x){
    	find(x);
    	node *p=root;
    	if(p==null) return NULL;
    	if(p->val<x) return p;
    	p=p->s[0];
    	while(p!=NULL && p->s[1]!=NULL)
    		p=p->s[1];
    	return p;
	}
	node *next_find(int x){
    	find(x);
    	node *p=root;
    	if(p==null) return NULL;
    	if(p->val>x) return p;
    	p=p->s[1];
    	while(p!=NULL && p->s[0]!=NULL)
    		p=p->s[0];
    	return p;
	}
	void erase(int x){
		node *p=find(x);
		if(p==NULL) return;
		if(p->cnt>1) p->cnt--,p->siz--;
		else if(p->s[0]!=null && p->s[1]!=NULL)
			root=null;
		else if(p->s[0]!=NULL)
			root=p->s[1],p->s[1]->fa=NULL;
		node *t=p->s[0];
		while(t->s[1]!=NULL) t=t->s[1];
		splay(t,null);
		link(root,p->s[1],1);
		link(NULL,root,1);
	}
};
tree p;
int main() {
	int t;
	cin>>t;
	p.insert(-INT_MAX),p.insert(INT_MAX);
	while(t--){
		int opt,x;
		cin>>opt>>x;
		if(opt==1) p.insert(x);
		if(opt==2) p.erase(x);
		if(opt==3) cout<<p.ranks(x)-1<<"\n";
		if(opt==4) cout<<p.get(x+1)<<"\n";
		if(opt==5) cout<<p.pre_find(x)->val<<"\n";
		if(opt==6) cout<<p.next_find(x)->val<<"\n";
	}
	return 0;
}
2023/6/27 18:13
加载中...