Description
您需要写一种数据结构(可参考题目标题),来维护一些数,其中需要提供以下操作:
1. 插入x数
2. 删除x数(若有多个相同的数,因只删除一个)
3. 查询x数的排名(若有多个相同的数,因输出最小的排名)
4. 查询排名为x的数
5. 求x的前驱(前驱定义为小于x,且最大的数)
6. 求x的后继(后继定义为大于x,且最小的数)
Input
第一行为n,表示操作的个数,下面n行每行有两个数opt和x,opt表示操作的序号(1<=opt<=6)
Output
对于操作3,4,5,6每行输出一个数,表示对应答案
平衡二叉树模板题。
涉及元素的插入、删除、查找。
splay版见http://blog.csdn.net/sdfzyhx/article/details/51429578。
替罪羊树版见http://blog.csdn.net/sdfzyhx/article/details/70212142。
#include<cstdio>
#include<cstring>
#include<cstdlib>
struct node
{
int l,r,v,x,size,cnt;
}t[100010],n1,n2;
int root,size;
void lt(int &p)
{
int x=t[p].r;
t[p].r=t[x].l;
t[x].l=p;
t[x].size=t[p].size;
t[p].size=t[t[p].l].size+t[t[p].r].size+t[p].cnt;
p=x;
}
void rt(int &p)
{
int x=t[p].l;
t[p].l=t[x].r;
t[x].r=p;
t[x].size=t[p].size;
t[p].size=t[t[p].l].size+t[t[p].r].size+t[p].cnt;
p=x;
}
void ins(int x,int &p)
{
if (p==0)
{
p=++size;
t[p].x=x;
t[p].v=rand();
t[p].cnt=t[p].size=1;
return;
}
t[p].size++;
if (t[p].x==x)
{
t[p].cnt++;
return;
}
if (t[p].x>x)
{
ins(x,t[p].l);
if (t[t[p].l].v<t[p].v) rt(p);
}
else
{
ins(x,t[p].r);
if (t[t[p].r].v<t[p].v) lt(p);
}
}
void del(int x,int &p)
{
if (p==0) return;
if (t[p].x==x)
{
if (t[p].cnt>1)
{
t[p].size--;
t[p].cnt--;
return;
}
else
{
if (t[p].l*t[p].r==0)
p=t[p].l+t[p].r;
else
{
if (t[t[p].l].v<t[t[p].r].v)
rt(p),del(x,p);
else
lt(p),del(x,p);
}
}
}
else
{
if (t[p].x>x)
t[p].size--,del(x,t[p].l);
else
t[p].size--,del(x,t[p].r);
}
}
int ran(int x,int p)
{
if (p==0) return 0;
if (t[p].x==x)
return t[t[p].l].size+1;
if (x<t[p].x)
return ran(x,t[p].l);
return ran(x,t[p].r)+t[t[p].l].size+t[p].cnt;
}
int que(int x,int p)
{
if (p==0) return 0;
if (x<=t[t[p].l].size) return que(x,t[p].l);
if (x<=t[t[p].l].size+t[p].cnt) return t[p].x;
return que(x-t[t[p].l].size-t[p].cnt,t[p].r);
}
int pre(int x,int p)
{
if (p==0) return -1;
if (t[p].x<x)
{
int y=pre(x,t[p].r);
if (y==-1) return t[p].x;
return y;
}
return pre(x,t[p].l);
}
int suc(int x,int p)
{
if (p==0) return -1;
if (t[p].x>x)
{
int y=suc(x,t[p].l);
if (y==-1) return t[p].x;
return y;
}
return suc(x,t[p].r);
}
int main()
{
int i,j,k,x,y,z,n;
scanf("%d",&n);
for (i=1;i<=n;i++)
{
scanf("%d%d",&x,&y);
if (x==1) ins(y,root);
if (x==2) del(y,root);
if (x==3) printf("%d\n",ran(y,root));
if (x==4) printf("%d\n",que(y,root));
if (x==5) printf("%d\n",pre(y,root));
if (x==6) printf("%d\n",suc(y,root));
}
}