hdu 2852 KiKi's K-Number(线段树)

题目看起来很容易让人当成是划分树,但其实是个挺水的线段树。

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值