K-th Number (二分+尺取) HDU6231

K-th Number
题面: 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.
N<=1e5
题意: 给你A数组,找出A数组中的所有子区间的第K大,所有第K大组成B数组,输出B数组第M大
思路: 我们要正着找出第M大复杂度N^2,但是我们可以反着来假设第M大,不断通过二分check正确性

#include
using namespace std;
typedef long long ll;
const int N=1e5+5;
int n,k;
ll m;
int a[N];
bool check(ll x)
{
    ll cnt=0,ans=0;
    int l=1;
    for(int i=1;i<=n;i++)
    {
        if(a[i]>=x)
            cnt++;
        if(cnt==k)
        {
            ans+=n-i+1;
            while(a[l]<x&&l<=i)
            {
                ans+=n-i+1;
                l++;
            }
            l++;
            cnt--;
        }
    }
    if(ans>=m)
        return 1;
    return 0;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d%lld",&n,&k,&m);
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        ll l=1,r=1e10;
        while(l<r)
        {
            ll mid=(l+r)>>1;
            if(check(mid))
            {
                l=mid+1;
            }
            else
                r=mid;
        }
        printf("%lld\n",l-1);
    }
    return 0;
}

你可能感兴趣的:(二分,尺取)