HDU2852-KiKi's K-Number(树状数组+二分|权值线段树)

KiKi’s K-Number

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4163 Accepted Submission(s): 1878

Problem Description
For the k-th number, we all should be very familiar with it. Of course,to kiki it is also simple. Now Kiki meets a very similar problem, kiki wants to design a container, the container is to support the three operations.

Push: Push a given element e to container

Pop: Pop element of a given e from container

Query: Given two elements a and k, query the kth larger number which greater than a in container;

Although Kiki is very intelligent, she can not think of how to do it, can you help her to solve this problem?

Input
Input some groups of test data ,each test data the first number is an integer m (1 <= m <100000), means that the number of operation to do. The next m lines, each line will be an integer p at the beginning, p which has three values:
If p is 0, then there will be an integer e (0

题意:

让你维护数据的插入删除,和求大于a的第K小元素

树状数组和权值线段树都可以维护好
对于树状数组求大于a的第K大元素,那么二分答案,然后getsum(mid)-getsum(x)>=k,一直二分下去即可
复杂度 O(nlog2n)

对于权值线段树,先求1-a的个数记为res,那么问题转化成求整个区间的res+k小,复杂度 O(nlogn)

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long LL;
const int maxn=1e5+5,N=100000+5;

int T[maxn],kase,n,p,k,kth,a[maxn];

inline int get(int x)
{
  int res=0;
  for(;x;x-=x&-x)res+=T[x];
  return res;
}

inline void add(int x,int val)
{
  for(;x<N;x+=x&-x)T[x]+=val;
}

inline int find(int x,int k)
{
  int L=x+1,R=N;
  while(L+1<R)
  {
    int mid=(L+R)>>1;
    if(get(mid)-get(x)>=k)R=mid;
    else L=mid;
  }
  if(get(L)-get(x)>=k)return L;
  else return R;
}

int main()
{
  while(~scanf("%d",&n))
  {
    memset(T,0,sizeof(T));
    memset(a,0,sizeof(a));
    for(int i=1;i<=n;++i)
    {
      scanf("%d%d",&p,&k);
      if(p==0)
      {
        add(k,+1);
        a[k]++;
      }
      if(p==1)
      {
        if(a[k]==0)
        {
          printf("No Elment!\n");
          continue;
        }
        add(k,-1);
        a[k]--;
      }
      if(p==2)
      {
        scanf("%d",&kth);

        if(get(100000)-get(k)<kth)
        {
          printf("Not Find!\n");
          continue;
        }
        int res=find(k,kth);
        printf("%d\n",res);
      }
    }
  }
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值