HDU 6231

K-th Number

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


php

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
 

 

Source
題意:
大小爲n的a數組,把其中全部的長度不小於k的區間中第k大的數加入到b數組,最後求b數組中的m大的數
輸入:
n,k,m
a[1~n];
代碼:
//m要用long long 啊。
//二分答案x,而後尺取。找到有多少個區間存在至少k個大於等於x的數,若是這樣的區間數很多於m個就說明第m大的數
//比x大,所以有單調性。尺取區間[l,r]中有k個不小於x的數那麼會有n-r+1個符合的區間。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const int MAXN=100009;
int n,k,a[MAXN];
ll m;
bool solve(int x)
{
    ll sum=0;
    int tmp=0,l=1,r=0;
    while(1){
        while(tmp<k){
            ++r;
            if(r>n) break;
            if(a[r]>=x) tmp++;
        }
        if(r>n) break;
        sum+=(n-r+1);
        if(a[l]>=x) tmp--;
        l++;
    }
    if(sum>=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]);
        int l=1,r=1e9,ans=0;
        while(l<=r){
            int mid=(l+r)>>1;
            if(solve(mid)) { ans=mid;l=mid+1; }
            else r=mid-1;
        }
        printf("%d\n",ans);
    }
    return 0;
}
相關文章
相關標籤/搜索