又是 机房最后一个学
s
p
l
a
y
splay
splay的人
参考
d
a
l
a
o
dalao
dalao博客
写的非常好!
最后放上我的代码:
(有个地方应该写
c
h
[
r
o
o
t
]
[
0
]
ch[root][0]
ch[root][0]手残写成
c
h
[
r
o
o
t
]
[
1
]
ch[root][1]
ch[root][1]还查不出来
T
T
T成狗
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define N 1000001
using namespace std;
int n,ch[N][2],f[N],siz[N],cnt[N],key[N],sz,root;
inline int rd(){
int x=0,f=1;char c=' ';
while(c<'0' || c>'9') f=c=='-'?-1:1,c=getchar();
while(c<='9' && c>='0') x=x*10+c-'0',c=getchar();
return x*f;
}
inline void clear(int x){//清空
ch[x][0]=ch[x][1]=f[x]=cnt[x]=key[x]=siz[x]=0;
}
inline int get(int x){return ch[f[x]][1]==x;}//找到x和f[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=f[x],oldf=f[old],wh=get(x);
f[ch[x][wh^1]]=old; ch[old][wh]=ch[x][wh^1];
f[old]=x; ch[x][wh^1]=old; f[x]=oldf;
if(oldf) ch[oldf][ch[oldf][1]==old]=x;
update(old); update(x);
}
inline void splay(int x){//旋转到根
for(int fa;(fa=f[x]);rotate(x))
if(f[fa])
rotate(get(x)==get(fa)?fa:x);
root=x;
}
inline void insert(int x){//插入
if(root==0) {
sz++; ch[sz][0]=ch[sz][1]=f[sz]=0; root=sz; siz[sz]=cnt[sz]=1;
key[sz]=x; return;
}
int now=root,fa=0;
while(1){
if(x==key[now]) {
cnt[now]++; update(now); update(fa); splay(now);
break;
}
fa=now;
now=ch[now][key[now]<x];
if(now==0){
sz++; ch[sz][0]=ch[sz][1]=0; f[sz]=fa;
siz[sz]=cnt[sz]=1; ch[fa][key[fa]<x]=sz;
key[sz]=x; update(fa); splay(sz);
break;
}
}
}
inline int find(int x){//查询x的排名
int now=root,ans=0;
while(1){
if(x<key[now]) now=ch[now][0];
else{
ans+=ch[now][0]?siz[ch[now][0]]:0;
if(x==key[now]) {
splay(now); return ans+1;
}
ans+=cnt[now];
now=ch[now][1];
}
}
}
inline int findx(int x){//查询排名为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 key[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){//删除一个x
int useless=find(x);
if(cnt[root]>1) {cnt[root]--;update(root);return;}
if(!ch[root][0] && !ch[root][1]) {clear(root);root=0;return;}//无儿子
if(!ch[root][0]){//一个儿子
int oldroot=root; root=ch[root][1]; f[root]=0; clear(oldroot);
return;
}
else if(!ch[root][1]){
int oldroot=root; root=ch[root][0]; f[root]=0; clear(oldroot);
return;//
}
int lf=pre(),oldroot=root;//两个儿子
splay(lf);
ch[root][1]=ch[oldroot][1]; f[ch[oldroot][1]]=root;
clear(oldroot); update(root); return;
}
int main(){
n=rd();
while(n--){
int opt=rd(),x=rd();
if(opt==1) insert(x);
if(opt==2) del(x);
if(opt==3) printf("%d\n",find(x));
if(opt==4) printf("%d\n",findx(x));
if(opt==5) {
insert(x); printf("%d\n",key[pre()]); del(x);
}
if(opt==6) {
insert(x); printf("%d\n",key[nxt()]); del(x);
}
}
return 0;
}