6051: KiKi's K-Number (树状数组)

增加一个数就update(x,1)

减去这个数就update(x,-1)

查看是否有某个数就query(x)-query(x-1)是否>0

看比a大k的数就二分查找query值为query(a)+k的数

http://www.tzcoder.cn/acmhome/problemdetail.do?&method=showdetail&id=6051

#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
int c[100005],a[100005];
int lowbit(int x)
{
    return x&-x;
}
int updata(int x,int y)
{
    while(x<=maxn){
        c[x]+=y;
        x+=lowbit(x);
    }
}
int query(int x)
{
    int sum=0;
    while(x){
        sum+=c[x];
        x-=lowbit(x);
    }
    return sum;
}
int main(){
    int n;
    while(~scanf("%d",&n)){
       memset(c,0,sizeof(c));
       while(n--){
            int p;
            scanf("%d",&p);
            if(p==0){
                int e;
                scanf("%d",&e);
                updata(e,1);
            }
            else if(p==1){
                int e;
                scanf("%d",&e);
                if(query(e)-query(e-1)==0)printf("No Element!\n");
                else updata(e,-1);
            }
            else {
                int a,k;
                scanf("%d%d",&a,&k);
                if(query(maxn)-query(a)<k)printf("Not Find!\n");
                else{
                    int answer=query(a)+k;
                    int l=0,r=maxn,mid;
                    while(l<=r){
                        mid=(l+r)/2;
                        if(query(mid)<answer)l=mid+1;
                        else r=mid-1;
                    }
                    printf("%d\n",l);
                }
            }
       }
    }
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/ydw--/p/11907878.html
今日推荐