您的位置:首页 > 其它

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

2017-11-12 16:03 267 查看

K-th Number

[b]Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)

Total Submission(s): 76    Accepted Submission(s): 26
[/b]

[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
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.

 

[align=left]Output[/align]
For each test case, output a single line containing the
M-th
largest element in the array B.
 

[align=left]Sample Input[/align]

2
5 3 2
2 3 1 5 4
3 3 1
5 8 2

 

[align=left]Sample Output[/align]

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: