2017CCPC哈尔滨 hdu 6231 B k-th number

Alice are given an array A[1..N]A[1..N] with NN numbers. 

Now Alice want to build an array BB by a parameter KK as following rules: 

Initially, the array B is empty. Consider each interval in array A. If the length of this interval is less than KK, then ignore this interval. Otherwise, find the KK-th largest number in this interval and add this number into array BB. 

In fact Alice doesn't care each element in the array B. She only wants to know the MM-th largest element in the array BB. Please help her to find this number.

Input

The first line is the number of test cases. 

For each test case, the first line contains three positive numbers N(1≤N≤105),K(1≤K≤N),MN(1≤N≤105),K(1≤K≤N),M. The second line contains NN numbers Ai(1≤Ai≤109)Ai(1≤Ai≤109). 

It's guaranteed that M is not greater than the length of the array B. 

Output

For each test case, output a single line containing the MM-th largest element in the array BB.

Sample Input

2
5 3 2
2 3 1 5 4
3 3 1
5 8 2

Sample Output

3
2

题意就是对所有大于等于K长度的区间 找到第K大的数 然后将这些数存入B后排序后输出 第M大的数

直接求或者模拟肯定是不可能  这里用了 对答案二分和用尺取法求区间数目的思想

刚开始自己没想到,队友想到了,看了题解才知道尺取法 

 

大致解法: 对于B数组中第M大的数 在原来数组里必然存在 M个区间并且对于每个区间必然有,这个所求的数为区间内第K大的数

所以我们可以通过求出所有满足 刚好有K个数大于等于某一个数X的区间数目 并与M作比较, 从而得出这个枚举的X与真正要求的

的大小关系,如果区间数目大于M 说明X小于真实值 ,区间数目小于M说明X大于真实值,从而可以对X的取值进行二分 得到我们要求的真实值。

代码 如下

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[100005];
int N;
int k;
long long M;
int t;
bool judge(int x)
{
    long long ans=0;   //区间数目
    int sum=0;    //大于等于x的数量
    int j=1;
    for(int i=1;i<=N;i++)
    {
        if(a[i]>=x)sum++;
        if(sum==k)
        {
            ans+=N-i+1;  // 后面指针向后移动的区间数目
            while(a[j]<x)
            {
                ans+=N-i+1;  //前面指针向后移动的区间数目
                j++;
            }
            j++;      //区间移动 尺取法 
            sum--;
        }
    }
    if(ans>=M)return true;
    else return false;
}

int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%lld",&N,&k,&M);
        for(int i=1;i<=N;i++)
        {
            scanf("%d",&a[i]);
        }
        int mi  = *min_element(a+1,a+N+1);   // 从最小到最大进行二分处理
        int ma = *max_element(a+1,a+N+1);
        int mid;
        while(mi<ma)
        {
            mid=ma-(ma-mi)/2;
            if(judge(mid))
            {
                mi=mid;
            }
            else ma=mid-1;
        }
        printf("%d\n",mi);
    }
    return 0;
}
注意:M要用longlong 否则可能溢出(实际wa了两发)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值