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.
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(1≤N≤105),K(1≤K≤N),M . The second line contains N numbers Ai(1≤Ai≤109) .
It's guaranteed that M is not greater than the length of the array B.
For each test case, the first line contains three positive numbers N(1≤N≤105),K(1≤K≤N),M . The second line contains N numbers 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
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;
}