2017CCPC哈尔滨站 K-th Number 【二分】

本文介绍了一种解决K-thNumber问题的有效算法。该问题要求找出数组中所有连续区间内的第K小元素所组成的数组里的第M大元素。文章详细阐述了如何利用二分查找与区间计数的方法来优化解决方案,确保复杂度可控。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

K-th Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 76    Accepted Submission(s): 26


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

Now Alice want to build an array
B by a parameter K as following rules:

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

In fact Alice doesn't care each element in the array B. She only wants to know the
M-th largest element in the array B. 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(1N105),K(1KN),M. The second line contains N numbers Ai(1Ai109).

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 M-th largest element in the array B.
 

Sample Input
2 5 3 2 2 3 1 5 4 3 3 1 5 8 2
 

Sample Output
3 2
 
题意:给出一个长度为N的数组a[i],问在这个数组中的所有连续区间中的第K小的数组成的数组b[i]中第M大的数。
思路难得,如果想得到所有区间中的第K小,达到O(n*n)很轻松,转换一下思路,一个区间中,如果第K小的数要大于最终答案,那么这个区间中至少要有K个数大于等于最终答案。我们设最终答案为x,且这个x满足有大于等于m个区间的第k小大于等于x,这个区间的数量我们可以通过枚举每一个区间的端点对于每个左端L,可以找一个最小的r使得,当右端点大于等于r时,[L,r]有k个数大于等于x。所以L为左端点的区间中满足要求的区间数有 n-r+1个,通过区间的数量与m的关系决定二分的走向。
#include<bits/stdc++.h>
using namespace std;
int n,m,k,a[100001];
long long find(int x)
{
    long long ans=0;
    int q=0;
    int out=0;
    for(int i=1;i<=n;i++){
        while(out<k&&q<=n){
            if(a[++q]>=x)
                out++;
        }
        ans+=n-q+1;
        if(a[i]>=x)
            out--;
    }
    return ans;
}
int main(){
    long long m;
    int t,l,r,mid;
    scanf("%d",&t);
    while(t--){
        scanf("%d%d%lld",&n,&k,&m);
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
        }
        l=1,r=1000000000;
        while(l<r)
        {
            mid=(l+r+1)/2;
            if(find(mid)>=m)
                l=mid;
            else
                r=mid-1;
        }
        printf("%d\n",r);
    }
    return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值