//目录

HDU 6231

K-th Number

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


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
 
 
还是有必要说一下题意吧:那个interval 翻译是间隔,理解为一个区间。
就是给定N个数,K,M,求>=k个数的连续区间里面第k大的数挑出来,形成一个新的数组A,求A的第M大的数。
 
分析:
当时队友要让我上名词树,ヘ(´o`)ヘ。
当然是算每一个数作为第k大,出现了几次,噼里啪啦的把A数组求好,但是这样递推计数好像挺复杂的。
 
答案揭晓:二分这个答案x,找出作为第M大的x,满足他的区间有多少个(这个查找是尺取查找)。当个数>=M,则x应该更大一点。
#include <bits/stdc++.h>

using namespace std;
const int maxn = 1e5 + 5;
int N,K;
long long M;
int a[maxn];

bool calc(int x)
{
    int cnt = 0;
    int p = 0;
    long long ans = 0;
    for(int i = 1; i <= N; i++) {
        while(cnt<K&&p<=N) {
            if(a[++p]>=x) {
                cnt++;
            }
        }
        ans += N - p + 1;
        if(a[i]>=x)
            cnt--;
    }
    return ans>=M;
}


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;
        int ret;
        while(L<=R) {
            int mid = (L+R)/2;
            if(calc(mid))
            {
                ret = mid;
                L = mid + 1;
            }
            else R = mid-1;
        }
        printf("%d\n",ret);
    }
    return 0;
}
View Code

坑点M是long long 型

posted @ 2017-11-12 21:24  小草的大树梦  阅读(315)  评论(0编辑  收藏  举报