第二代Splay魔板。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int fa[100005],ch[100005][2],cnt[100005],size[100005],k[100005],m,ind=0,root=0;
void update(int p){
size[0]=0;ch[0][0]=ch[0][1]=0;
size[p]=size[ch[p][0]]+size[ch[p][1]]+cnt[p];
}
int search(int v){
int p=root;
while(p&&k[p]!=v)p=ch[p][k[p]<v];
return p;
}
void rotate(int p){
int q=fa[p],y=fa[q],x=ch[q][1]==p;
ch[q][x]=ch[p][x^1];fa[ch[q][x]]=q;
ch[p][x^1]=q;fa[q]=p;fa[p]=y;
if(y)if(ch[y][0]==q)ch[y][0]=p;
else if(ch[y][1]==q)ch[y][1]=p;
update(q);update(p);
}
void splay(int x){
for(int y;y=fa[x];rotate(x))
if(fa[y])rotate((x==ch[y][0])==(y==ch[fa[y]][0])?y:x);
root=x;
}
void insert(int v){
if(root){
if(search(v)){
int t=search(v);
splay(t);
size[t]++;cnt[t]++;
}
else{
int x=root,y;
while(1){
y=ch[x][k[x]<v];
if(!y){
y=++ind;
k[y]=v;
ch[y][0]=ch[y][1]=0;
fa[y]=x;
ch[x][k[x]<v]=y;
cnt[y]=1;size[y]=1;
break;
}
x=y;
}
splay(y);
}
}
else{
root=++ind;
k[root]=v;
ch[root][0]=ch[root][1]=fa[root]=0;
size[root]=1;cnt[root]=1;
}
}
void remove(int p){
if(!p)return;
splay(p);
if(cnt[p]>1){
cnt[p]--;
size[p]--;
return;
}
int l=ch[p][0],r=ch[p][1];
ch[p][0]=ch[p][1]=0;
if(l)fa[l]=0;
if(r)fa[r]=0;
root=l;
int t=l;
while(t&&ch[t][1])t=ch[t][1];
if(t==0){
root=r;
return;
}
splay(t);
ch[t][1]=r;
fa[r]=t;
update(root);
}
int grank(int p){
splay(p);
return size[ch[p][0]]+1;
}
int kth(int _k){
int t=root,k=_k;
while(t){
if(ch[t][0]){
if(size[ch[t][0]]<=k-1&&size[ch[t][0]]+cnt[t]>=k)return t;
if(size[ch[t][0]]>k-1)t=ch[t][0];
else k-=(size[ch[t][0]]+cnt[t]),t=ch[t][1];
}
else{
if(k<=cnt[t])return t;
else k-=cnt[t],t=ch[t][1];
}
}
return 0;
}
int prefix(int p){
splay(p);
int t=ch[p][0];
while(t&&ch[t][1])t=ch[t][1];
return t;
}
int suffix(int p){
splay(p);
int t=ch[p][1];
while(t&&ch[t][0])t=ch[t][0];
return t;
}
int main(){
scanf("%d",&m);
for(int i=0;i<m;i++){
int t1,t2;
scanf("%d%d",&t1,&t2);
switch(t1){
case 1:{
insert(t2);
break;
}
case 2:{
remove(search(t2));
break;
}
case 3:{
printf("%d\n",grank(search(t2)));
break;
}
case 4:{
printf("%d\n",k[kth(t2)]);
break;
}
case 5:{
insert(t2);
printf("%d\n",k[prefix(search(t2))]);
remove(search(t2));
break;
}
case 6:{
insert(t2);
printf("%d\n",k[suffix(search(t2))]);
remove(search(t2));
break;
}
}
}
return 0;
}
每次写模板,调试花的时间总是写的时间的三倍以上……写下这行字前觉得可以说的很多,但突然间竟感到渺茫……