splay P3369普通平衡树
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define FL(a, b, c) for(int a = (b), a##end = (c); a <= a##end; a++)
#define FR(a, b, c) for(int a = (b), a##end = (c); a >= a##end; a--)
#define lowbit(x) ((x) & -(x))
constexpr int N = 1e6 + 10;
struct Splay{
struct node{int size, val, ch[2], fa;}d[N];
#define ls(x) d[x].ch[0]
#define rs(x) d[x].ch[1]
#define fa(x) d[x].fa
int root, tot = 0, stk[N], top;
int newnode(int val){
int w = top ? stk[top--] : ++tot;
d[w].size = 1, d[w].val = val, ls(w) = rs(w) = fa(w) = 0;
return w;
}
void pushup(int x){d[x].size = 1 + d[ls(x)].size + d[rs(x)].size;}
#define delnode(x) stk[++top] = x
bool get(int x){return x == rs(fa(x));}
void rotate(int x){
int y = fa(x), z = fa(y), c = get(x);
if(d[x].ch[!c])fa(d[x].ch[!c]) = y;
d[y].ch[c] = d[x].ch[!c], d[x].ch[!c] = y, fa(y) = x, fa(x) = z;
if(z) d[z].ch[y == d[z].ch[1]] = x;
pushup(y), pushup(x);
}
void splay(int x){
for(int f = fa(x); f = fa(x), f; rotate(x))
if(fa(f))rotate(get(f) == get(x) ? f : x);
root = x;
}
void insert(int val){
int now = root, f = 0;
while(now) f = now, now = d[now].ch[val > d[now].val];
now = newnode(val), fa(now) = f, d[f].ch[val > d[f].val] = now, splay(now);
}
void del(int val){
int now = root, f = 0;
while(d[now].val != val && now)f = now, now = d[now].ch[val > d[now].val];
if(!now)return splay(f);
splay(now);
int cur = ls(now);
if(!cur)return root = rs(now), fa(rs(now)) = 0, delnode(now), void();
while(rs(cur)) cur = rs(cur);
rs(cur) = rs(now), fa(rs(now)) = cur, fa(ls(now)) = 0, delnode(now);
pushup(cur), splay(cur);
}
int query_rank(int val){
int ans = 1, now = root, f;
while(now)
if(d[f = now].val < val)ans += d[ls(now)].size + 1, now = rs(now);
else now = ls(now);
return splay(f), ans;
}
int kth(int rak){
int now = root, siz;
while(now){
if((siz = d[ls(now)].size + 1) > rak) now = ls(now);
else if(!(rak -= siz)) break;
else now = rs(now);
}
return splay(now), d[now].val;
}
int ask_pre(int val){
int now = root, ans = -1e9, f;
while(now)
if(d[f = now].val >= val)now = ls(now);
else ans = d[now].val, now = rs(now);
return splay(f), ans;
}
int ask_next(int val){
int now = root, ans = 0, f;
while(now)
if(d[f = now].val <= val)now = rs(now);
else ans = d[now].val, now = ls(now);
return splay(f),ans;
}
}T;
int32_t main(){
cin.tie(0)->sync_with_stdio(0);
int n;
cin >> n;
while(n--){
int op, x;
cin >> op >> x;
switch(op){
case 1:T.insert(x);break;
case 2:T.del(x);break;
case 3:cout << T.query_rank(x) << endl;break;
case 4:cout << T.kth(x) << endl;break;
case 5:cout << T.ask_pre(x) << endl;break;
case 6:cout << T.ask_next(x) << endl;break;
}
}
return 0;
}