RT,WA+1个TLE
#include <iostream>
#include <cstdio>
#include <algorithm>
#define rint register int
#define endl '\n'
const int N = 5e5 + 5;
int root, idx;
struct Splay
{
struct Node
{
int s[2], fa;
int val, cnt;
int size; //儿子数量
void init(int _val, int _fa)
{
val = _val, fa = _fa;
size = cnt = 1;
}
void clear()
{
s[0] = s[1] = 0;
fa = 0;
val = cnt = 0;
size = 0;
}
} t[N];
void push_up(int p)
{
t[p].size = t[t[p].s[0]].size + t[t[p].s[1]].size + 1;
}
void rotate(int x)
{
int y = t[x].fa;
int z = t[y].fa;
int k = t[y].s[1] == x;
t[z].s[t[z].s[1] == y] = x;
t[x].fa = z;
t[y].s[k] = t[x].s[k ^ 1];
t[t[x].s[k ^ 1]].fa = y;
t[x].s[k ^ 1] = y;
t[y].fa = x;
push_up(y);
push_up(x);
}
void splay(int x, int k)
{
while (t[x].fa != k)
{
int y = t[x].fa;
int z = t[y].fa;
if (z != k)
{
if ((t[y].s[1] == x) ^ (t[z].s[1] == y))
{
rotate(x);
}
else
{
rotate(y);
}
}
rotate(x);
}
if (k == 0)
{
root = x;
}
}
void insert(int k)
{
if (root == 0)
{
t[++idx].init(k, 0);
root = idx;
return;
}
int p = root, fa = 0;
while (1)
{
if (t[p].val == k)
{
t[p].cnt++;
push_up(p);
push_up(fa);
splay(p, 0);
break;
}
fa = p;
p = t[p].s[t[p].val < k];
if (p == 0)
{
t[++idx].init(k, fa);
t[fa].s[t[fa].val < k] = idx;
push_up(fa);
splay(idx, 0);
break;
}
}
}
int find(int k)
{
int res = 0, p = root;
while (1)
{
if (k < t[p].val)
{
p = t[p].s[0];
}
else
{
if (t[p].s[0])
{
res += t[t[p].s[0]].size;
}
if (k == t[p].val)
{
splay(p, 0);
return res + 1;
}
res += t[p].cnt;
p = t[p].s[1];
}
}
}
int kth_number(int k)
{
int p = root;
while (1)
{
if (t[t[p].s[0]].size >= k && t[p].s[0])
{
p = t[p].s[0];
}
else
{
k -= t[p].cnt;
if (t[p].s[0])
{
k -= t[t[p].s[0]].size;
}
if (k <= 0)
{
splay(p, 0);
return t[p].val;
}
p = t[p].s[1];
}
}
}
int prev()
{
int p = t[root].s[0];
if (p == 0)
{
return p;
}
while (t[p].s[1])
{
p = t[p].s[1];
}
splay(p, 0);
return p;
}
int next()
{
int p = t[root].s[1];
if (p == 0)
{
return p;
}
while (t[p].s[0])
{
p = t[p].s[0];
}
splay(p, 0);
return p;
}
int get_prev()
{
return t[prev()].val;
}
int get_next()
{
return t[next()].val;
}
void del(int k)
{
find(k);
if (t[root].cnt > 1)
{
t[root].cnt--;
push_up(root);
return;
}
if (!t[root].s[0] && !t[root].s[1])
{
t[root].clear();
root = 0;
return;
}
if (!t[root].s[0])
{
int p = root;
root = t[root].s[1];
t[root].fa = 0;
t[p].clear();
return;
}
if (!t[root].s[1])
{
int p = root;
root = t[root].s[0];
t[root].fa = 0;
t[p].clear();
return;
}
int p = root;
int x = prev();
t[t[p].s[1]].fa = x;
t[x].s[1] = t[p].s[1];
t[p].clear();
push_up(root);
}
} tree;
int n;
int main()
{
scanf("%d", &n);
while (n--)
{
int op, x;
scanf("%d%d", &op, &x);
if (op == 1)
tree.insert(x);
if (op == 2)
tree.del(x);
if (op == 3)
printf("%d\n", tree.find(x));
if (op == 4)
printf("%d\n", tree.kth_number(x));
if (op == 5)
tree.insert(x), printf("%d\n", tree.get_prev()), tree.del(x);
if (op == 6)
tree.insert(x), printf("%d\n", tree.get_next()), tree.del(x);
}
return 0;
}