P3369,splay平衡树蜜汁tle,求大佬们帮忙看看QWQ
#include <bits/stdc++.h>
#define ls t[p].l
#define rs t[p].r
using namespace std;
int n,idx,root;
struct node{
int l,r,cnt,size,val,fat;
} t[100010];
int New(int x,int u){
t[++idx].val=x,t[idx].fat=u;
if (x<t[u].val) t[u].l=idx;
else t[u].r=idx;
return idx;
}
void pushup(int p){
t[p].size=t[ls].size+t[rs].size+t[p].cnt;
return;
}
void rotate(int p){
int u=t[p].fat,v=t[u].fat;
if (!t[u].cnt) return;
if (t[u].l==p){
t[u].l=rs,t[p].r=u;
if (t[rs].cnt) t[rs].fat=u;
}
else{
t[u].r=ls,t[p].l=u;
if (t[ls].cnt) t[ls].fat=u;
}
t[u].fat=p,t[p].fat=v;
if (t[v].cnt){
if (t[v].l==u) t[v].l=p;
else t[v].r=p;
}
pushup(u);pushup(p);
return;
}
void splay(int p,int gl){
int u,v;
while ((u=t[p].fat)!=gl && (v=t[u].fat)!=gl){
if ((t[v].l==u && t[u].l==p) || (t[v].r==u && t[u].r==p)){
rotate(u);rotate(p);
}
else{
rotate(p);rotate(p);
}
}
if (v==gl) rotate(p);
if (!gl) root=p;
return;
}
void find(int x){
int p=root;
while (t[p].val!=x){
if (x<t[p].val && t[ls].cnt) p=ls;
else if (t[p].val<x && t[rs].cnt) p=rs;
else break;
}
splay(p,0);
return;
}
void insert(int x){
int p=root,u=root;
while (t[p].val!=x){
if (x<t[p].val) p=ls;
else p=rs;
if (!t[p].cnt || !p){
p=New(x,u);
break;
}
u=p;
}
t[p].cnt++;
pushup(p);
splay(p,0);
return;
}
int Rank(int x){
find(x);
if (t[root].val<x) return t[t[root].l].size+t[root].cnt;
return t[t[root].l].size;
}
int Val(int rk){
int p=root;
while (1){
if (rk<t[ls].size) p=ls;
else if (t[ls].size<=rk && rk<t[ls].size+t[p].size) break;
else p=rs;
}
splay(p,0);
return t[p].val;
}
int Pre(int x){
find(x);
if (t[root].val<x) return root;
int p=t[root].l;
while (t[rs].cnt && rs) p=rs;
splay(p,0);
return p;
}
int Nxt(int x){
find(x);
if (x<t[root].val) return root;
int p=t[root].r;
while (t[ls].cnt && ls) p=ls;
splay(p,0);
return p;
}
void del(int x){
int nxt=Nxt(x),pre=Pre(x);
splay(nxt,pre);
int p=t[nxt].l;
if (t[p].cnt>1){
t[p].cnt--;splay(p,0);
}
else t[p].cnt=0,t[p].fat=0,t[p].size=0,t[nxt].l=0;splay(nxt,0);
return;
}
int main(){
insert(INT_MAX);insert(INT_MIN);
scanf("%d",&n);
int opt,x;
for (int i=1;i<=n;i++){
scanf("%d %d",&opt,&x);
if (opt==1) insert(x);
else if (opt==2) del(x);
else if (opt==3) printf("%d\n",Rank(x));
else if (opt==4) printf("%d\n",Val(x));
else if (opt==5) printf("%d\n",t[Pre(x)].val);
else if (opt==6) printf("%d\n",t[Nxt(x)].val);
}
return 0;
}