using namespace std;
const int N = 2e5+5;
const int inf = 0x3f3f3f3f;
struct Node
{
int ch[2], val, si, cnt;
int mi, mx, ans;
int da;
} tr[N] ;
int root, tot;
int newnode(int v)
{
tr[++tot].val = v;
tr[tot].da = rand();
tr[tot].si = 1;
tr[tot].cnt = 1;
return tot;
}
inline void pushup(int p)
{
tr[p].si = tr[tr[p].ch[0]].si + tr[tr[p].ch[1]].si + tr[p].cnt;
}
void build()
{
root = newnode(-inf), tr[root].ch[1] = newnode(inf);
pushup(root);
}
void ro(int &now, int v)
{
int te = tr[now].ch[v^1];
tr[now].ch[v^1] = tr[te].ch[v];
tr[te].ch[v] = now;
now = te;
pushup(tr[now].ch[v]); pushup(now);
}
void ins(int v, int & now = root)
{
if (!now)
{ now = newnode(v); return; }
if (v == tr[now].val) tr[now].cnt++;
else
{
int d = v < tr[now].val ? 0 : 1;
ins(v, tr[now].ch[d]);
if (tr[now].da < tr[tr[now].ch[d]].da)
ro(now, d ^ 1);
}
pushup(now);
}
void del(int v, int & now = root)
{
if (!now) return;
if (v == tr[now].val)
{
if (tr[now].cnt > 1) {tr[now].cnt--; pushup(now); return ;}
if (tr[now].ch[0] || tr[now].ch[1])
{
if (!tr[now].ch[1] || tr[tr[now].ch[0]].da > tr[tr[now].ch[1]].da)
{ ro(now, 1); del(v, tr[now].ch[1]); }
else {ro(now, 0); del(v, tr[now].ch[0]); }
pushup(now);
}
else now = 0;
return ;
}
v < tr[now].val ? del(v, tr[now].ch[0]) : del(v, tr[now].ch[1]);
pushup(now);
}
int get_rank(int v, int now = root)
{
if (!now) return 0;
if (v == tr[now].val) return tr[tr[now].ch[0]].si + 1;
else if (v < tr[now].val) return get_rank(v, tr[now].ch[0]);
else return tr[tr[now].ch[0]].si + tr[now].cnt + get_rank(v, tr[now].ch[1]);
}
int get_val(int ran, int now = root)
{
if (!now) return inf;
if (ran <= tr[tr[now].ch[0]].si)
return get_val(ran, tr[now].ch[0]);
else if (ran <= tr[tr[now].ch[0]].si + tr[now].cnt)
return tr[now].val;
else return get_val(ran - tr[tr[now].ch[0]].si - tr[now].cnt, tr[now].ch[1]);
}
int get_pre(int v)
{
int now = root, pre;
while(now)
{
if (tr[now].val < v) pre = tr[now].val, now = tr[now].ch[1];
else now = tr[now].ch[0];
}
return pre;
}
int get_ne(int v)
{
int now = root, ne;
while(now)
{
if (tr[now].val > v) ne = tr[now].val, now = tr[now].ch[0];
else now = tr[now].ch[1];
}
return ne;
}
int main()
{
int n;
build();//不要忘记初始化[运行build()会连同root一并初始化,所以很重要]
scanf("%d", &n);
for(int i = 1;i <= n;i++){
int cmd, x;
scanf("%d%d", &cmd, &x);
if(cmd == 1)ins(x);//函数都写好了,注意:需要递归的函数都从根开始,不需要递归的函数直接查询
else if(cmd == 2)del(x);
else if(cmd == 3)printf("%d\n",get_rank(x) - 1);//注意:因为初始化时插入了INF和-INF,所以查询排名时要减1(-INF不是第一小,是“第零小”)
else if(cmd == 4)printf("%d\n",get_val(x + 1));//同理,用排名查询值得时候要查x + 1名,因为第一名(其实不是)是-INF
else if(cmd == 5)printf("%d\n",get_pre(x));
else if(cmd == 6)printf("%d\n",get_ne(x));
}
return 0;
}
Treap树(插入、删除、前驱后继、排名数、数排名)
最新推荐文章于 2022-11-21 15:16:39 发布