bzoj 3224 普通平衡树 包含此模板全部操作,可以提交至此。
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
const int maxn=
500005;
int fa[maxn],ch[maxn][
2],dat[maxn],cnt[maxn],siz[maxn],sz,root;
int n;
inline void clear(
int x){
ch[x][
0]=ch[x][
1]=fa[x]=cnt[x]=dat[x]=siz[x]=
0;
}
inline int get(
int x){
return ch[fa[x]][
1]==x;
}
inline void update(
int x){
if(x){
siz[x]=cnt[x];
if(ch[x][
0])siz[x]+=siz[ch[x][
0]];
if(ch[x][
1])siz[x]+=siz[ch[x][
1]];
}
}
inline void rotate(
int x){
int old=fa[x],oldf=fa[old],wh=get(x);
ch[old][wh]=ch[x][wh^
1];
fa[ch[old][wh]]=old;
fa[old]=x;
ch[x][wh^
1]=old;
fa[x]=oldf;
if(oldf){
ch[oldf][ch[oldf][
1]==old]=x;
}
update(old);
update(x);
} splay(
int x){
for(
int f;f=fa[x];rotate(x)){
if(fa[f])rotate((get(x)==get(f)?f:x));
}
root=x;
}
inline void insert(
int v){
if(root==
0){
sz++;ch[sz][
0]=ch[sz][
1]=fa[sz]=
0;
dat[sz]=v;cnt[sz]=
1;siz[sz]=
1;root=sz;
return;
}
int now=root,f=
0;
while(
1){
if(dat[now]==v){
cnt[now]++;
update(now);
update(f);
splay(now);
break;
}
f=now;
now=ch[now][dat[now]<v];
if(now==
0){
sz++;
ch[sz][
0]=ch[sz][
1]=
0;
dat[sz]=v;
siz[sz]=
1;
cnt[sz]=
1;
fa[sz]=f;
ch[f][dat[f]<v]=sz;
update(f);
splay(sz);
break;
}
}
}e
int find(
int v){
int ans=
0,now=root;
while(
1){
if(v<dat[now])now=ch[now][
0];
else{
ans+=(ch[now][
0]?siz[ch[now][
0]]:
0);
if(v==dat[now]){splay(now);
return ans+
1;}
ans+=cnt[now];
now=ch[now][
1];
}
}
}
inline int findx(
int x){
int now=root;
while(
1){
if(ch[now][
0]&&x<=siz[ch[now][
0]]){
now=ch[now][
0];
}
else{
int tmp=(ch[now][
0]?siz[ch[now][
0]]:
0)+cnt[now];
if(x<=tmp)
return dat[now];
x-=tmp;
now=ch[now][
1];
}
}
}
inline int pre(){
int now=ch[root][
0];
while(ch[now][
1])now=ch[now][
1];
return now;
}
inline int nxt(){
int now=ch[root][
1];
while(ch[now][
0])now=ch[now][
0];
return now;
}
inline void del(
int x){
int wh=find(x);
if(cnt[root]>
1){cnt[root]--;
return;}
if(!ch[root][
0]&&!ch[root][
1]){clear(root);root=
0;
return;}
if(!ch[root][
0]){
int oldr=root;
root=ch[root][
1];
fa[root]=
0;
clear(oldr);
return;
}
else if(!ch[root][
1]){
int oldr=root;
root=ch[root][
0];
fa[root]=
0;
clear(oldr);
return;
}
int lb=pre();
int oldr=root;
splay(lb);
fa[ch[oldr][
1]]=root;
ch[root][
1]=ch[oldr][
1];
clear(oldr);
update(root);
return;
}
inline int prex(
int x){
insert(x);
int ans=pre();
del(x);
return dat[ans];
}
inline int nxtx(
int x){
insert(x);
int ans=nxt();
del(x);
return dat[ans];
}
int main(){
scanf(
"%d",&n);
int opt,xx;
while(n--){
scanf(
"%d%d",&opt,&xx);
if(opt==
1){
insert(xx);
continue;
}
if(opt==
2){
del(xx);
continue;
}
if(opt==
3){
printf(
"%d\n",find(xx));
continue;
}
if(opt==
4){
printf(
"%d\n",findx(xx));
continue;
}
if(opt==
5){
printf(
"%d\n",prex(xx));
continue;
}
if(opt==
6){
printf(
"%d\n",nxtx(xx));
continue;
}
}
return 0;
}
转载请注明原文地址: https://ju.6miu.com/read-664047.html