题目看起来很容易让人当成是划分树,但其实是个挺水的线段树。
0就是插入一个值,1就是删除一个值,如果树中不存在,就输出No Elment!2的话就是寻找树中从a开始往右查的第k个值。
因为值最大为100000,建树的时候以插入的值的范围建树。
#include<stdio.h>
#include<string.h>
#define N 100005
struct node
{
int x,y;
int cnt;
}a[N*3];
void CreatTree(int t,int x,int y)
{
a[t].x=x;
a[t].y=y;
a[t].cnt=0;
if(x==y)
return ;
int temp=t*2;
int mid=(x+y)/2;
CreatTree(temp,x,mid);
CreatTree(temp+1,mid+1,y);
return ;
}
void InsertTree(int t,int x)
{
if(a[t].x==a[t].y)
{
a[t].cnt++;
return ;
}
int temp=t*2;
int mid=(a[t].x+a[t].y)/2;
if(x<=mid)
InsertTree(temp,x);
else
InsertTree(temp+1,x);
a[t].cnt=a[temp].cnt+a[temp+1].cnt;
return ;
}
int DeleteTree(int t,int x)
{
int flag=0;
if(a[t].cnt==0)
return -1;
if(a[t].x==a[t].y)
{
a[t].cnt--;
return 0;
}
int temp=t*2;
int mid=(a[t].x+a[t].y)/2;
if(x<=mid)
flag=DeleteTree(temp,x);
else
flag=DeleteTree(temp+1,x);
a[t].cnt=a[temp].cnt+a[temp+1].cnt;
return flag;
}
int FindTree(int t,int x)
{
if(a[t].cnt<x)
return -1;
if(a[t].x==a[t].y)
return a[t].x;
int temp=t*2;
int mid=(a[t].x+a[t].y)/2;
if(x<=a[temp].cnt)
return FindTree(temp,x);
else
return FindTree(temp+1,x-a[temp].cnt);
}
int Find(int t,int x,int y)
{
if(a[t].x==x&&a[t].y==y)
return a[t].cnt;
int temp=t*2;
int mid=(a[t].x+a[t].y)/2;
if(y<=mid)
return Find(temp,x,y);
else if(x>mid)
return Find(temp+1,x,y);
else
return Find(temp,x,mid)+Find(temp+1,mid+1,y);
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
CreatTree(1,1,100000);
while(n--)
{
int p;
scanf("%d",&p);
if(p==0)
{
int x;
scanf("%d",&x);
InsertTree(1,x);
}
else if(p==1)
{
int x;
int t;
scanf("%d",&x);
t=DeleteTree(1,x);
if(t==-1)
printf("No Elment!\n");
}
else
{
int x,y;
scanf("%d%d",&x,&y);
int t;
t=Find(1,1,x);
t=t+y;
int temp;
temp=FindTree(1,t);
if(temp!=-1)
printf("%d\n",temp);
else
printf("Not Find!\n");
}
}
}
return 0;
}