#include<cstdio>
#include<iostream>
#include<cstdlib>
using namespace std;
const int MIN=-19999999;
const int MAX= 19999999;
struct node{
int key,siz,cnt;
node* ch[2],*pnt;
node(){}
node(int x,int y,int z):key(x),siz(y),cnt(z){}
void rs(){siz=ch[0]->siz+ch[1]->siz+cnt;}
};
node nil(0,0,0);
typedef node* pnode;
pnode null=&nil,root=null;
void rotate(pnode x, bool d){
pnode y=x->pnt;
y->ch[!d]=x->ch[d];
if(x->ch[d]!=null)x->ch[d]->pnt=y;
x->pnt=y->pnt;
if(y->pnt!=null){
if(y == y->pnt->ch[0])
y->pnt->ch[0]=x;
else
y->pnt->ch[1]=x;
}
x->ch[d]=y;y->pnt=x;
y->rs();x->rs();
}
void splay(pnode x,pnode tar){
pnode y;
while(x->pnt != tar){
y=x->pnt;
if(x == y->ch[0]){
if(y->pnt!=tar && y == y->pnt->ch[0])
rotate(y,1);
rotate(x,1);
}else{
if(y->pnt!=tar && y == y->pnt->ch[1])
rotate(y,0);
rotate(x,0);
}
}
if(tar == null)root=x;
}
void ins(int key){
if(root == null){
root=new struct node(key,1,1);
root->ch[0]=root->ch[1]=root->pnt=null;
return;
}
pnode x=root,y;
while(1){
x->siz++;
if( key == x->key ){
x->cnt++;
x->rs();
y=x;
break;
}else{
bool fg=(key > x->key);
if(x->ch[fg] != null)x=x->ch[fg];
else{
y=new struct node(key,1,1);
x->ch[fg]=y;
y->ch[1]=y->ch[0]=null;
y->pnt=x;
break;
}
}
}
splay(y,null);
}
pnode search(int key){
if (root == null) return null;
pnode x=root,y=null;
while(1){
if(key == x->key){
y=x;break;
}else{
bool fg=key > x->key;
if(x->ch[fg] != null)x=x->ch[fg];
else break;
}
}
splay(x,null);
return y;
}
pnode searchmin(pnode x){
pnode y=x->pnt;
while(x->ch[0]!=null)x=x->ch[0];
splay(x,y);
return x;
}
void del(int key){
if(root == null)return;
pnode x=search(key),y;
if(x == null)return;
if(x->cnt > 1){x->cnt--;x->rs();return;}
else if(x->ch[0]==null && x->ch[1]==null){root=null;return;}
else if(x->ch[0]==null){root=x->ch[1];x->ch[1]->pnt=null;return;}
else if(x->ch[1]==null){root=x->ch[0];x->ch[0]->pnt=null;return;}
y=searchmin(x->ch[1]);
y->pnt=null;
y->ch[0]=x->ch[0];
x->ch[0]->pnt=y;
y->rs();
root=y;
}
void order(pnode t){
if(t == null)return;
order(t->ch[0]);
for(int i=1;i<=t->cnt;i++)printf("%d ",t->key);
order(t->ch[1]);
}
int quer_no(int key){
pnode t=search(key);
return t==null?-1:t->ch[0]->siz+1;
}
int find_k(int k){
pnode t=root,ret;
while(k && t!=null){
if(t->ch[0]->siz < k && t->ch[0]->siz+t->cnt>=k)ret=t;
if(t->ch[0]->siz >= k)t=t->ch[0];
else{
k -= t->ch[0]->siz+t->cnt;
t=t->ch[1];
}
}
splay(ret,null);
return ret->key;
}
int pred(pnode t,int x){
if(t == null)return MIN;
if(x <= t->key) return pred(t->ch[0],x);
return max(t->key,pred(t->ch[1],x));
}
int succ(pnode t,int x){
if(t == null)return MAX;
if(x >= t->key) return succ(t->ch[1],x);
return min(t->key,succ(t->ch[0],x));
}
int fg,x,n;
int main(){
scanf("%d",&n);
while(n--){
scanf("%d%d",&fg,&x);
switch(fg){
case 1:
ins(x);break;
case 2:
del(x);break;
case 3:
printf("%d\n",quer_no(x));break;
case 4:
printf("%d\n",find_k(x));break;
case 5:
printf("%d\n",pred(root,x));break;
case 6:
printf("%d\n",succ(root,x));break;
}
}
}
splay模版
最新推荐文章于 2024-05-06 23:29:48 发布