模板:luogu P3369 【模板】普通平衡树
code:
#include <cstdio>
#include <cstdlib>
const int MAX_N=100010;
int rd() {
int x=0,fla=1; char c=' ';
while(c<'0' or c>'9') {c=getchar();if(c=='-') fla=-fla;}
while(c>='0' and c<='9') x=x*10+c-'0',c=getchar();
return x*fla;
}
struct node{
node *ch[2]; int data,key,size;
node () {}
node(int w,node *son) {ch[0]=ch[1]=son, data=w, key=rand(), size=1;}
void updata () {size = ch[0]->size + ch[1]->size +1;}
}nil,t[MAX_N],*null,*len,*root;;
void init() {
nil=node(0,NULL); null= &nil;
null->ch[0]=null->ch[1]=null;
null->size=0; len=t; root=null;
}
node* newnode(int x) {
*len=node(x,null);
return len++;
}
node* merge(node* a,node* b) {
if(a==null or b==null) return a==null?b:a;
if(a->key > b->key) {a->ch[1]=merge(a->ch[1],b); a->updata(); return a;}
else {b->ch[0]=merge(a,b->ch[0]); b->updata(); return b;}
}
void split(node* x,int k,node* &l,node* &r) {
if(x==null) {l=r=null;return ;}
if(x->data <= k) {l=x; split(l->ch[1],k,l->ch[1],r);}
else {r=x; split(r->ch[0],k,l,r->ch[0]);}
x->updata();
}
void insert(int k) {
node *l,*r; split(root,k,l,r);
root=merge(merge(l,newnode(k)),r);
}
void erase(int k) {
node *l,*mid,*r; split(root,k-1,l,r); split(r,k,mid,r);
root=merge(l,merge(merge(mid->ch[0],mid->ch[1]) ,r));
}
int kth(node *x,int k) {
if(k <= x->ch[0]->size) return kth(x->ch[0],k);
else if(k > x->ch[0]->size+1) return kth(x->ch[1],k - x->ch[0]->size-1);
return x->data;
}
int find(node *x,int d) {
while(x->ch[d]!=null) x=x->ch[d];
return x->data;
}
int main() {
init(); int q=rd(),c; node *l,*r;
while(q--)
switch(c=rd()) {
case 1:insert(rd());break;
case 2:erase(rd());break;
case 3:split(root,rd()-1,l,r);printf("%d
",l->size+1);root=merge(l,r);break;
case 4:printf("%d
",kth(root,rd()));break;
case 5:split(root,rd()-1,l,r);printf("%d
",find(l,1));root=merge(l,r);break;
case 6:split(root,rd(),l,r);printf("%d
",find(r,0));root=merge(l,r);break;
}
return 0;
}