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
#include
#include
#include
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(;xinline int find(int x,int k)
{
  int L=x+1,R=N;
  while(L+1int 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)printf("Not Find!\n");
          continue;
        }
        int res=find(k,kth);
        printf("%d\n",res);
      }
    }
  }
  return 0;
}

你可能感兴趣的:(权值线段树,二分,树状数组)