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.
Input
The first line is the number of test cases.
For each test case, the first line contains three positive numbers N(1≤N≤10^5),K(1≤K≤N),M. The second line contains N numbers Ai(1≤Ai≤10^9).
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个数字,其中的所有数量大于等于k的区间中选取第k大的数字放到另一个数组中,最后求另一个数组中第m大的数字~
这里简单的判断,直接求出另一个数组,然后得到第m大优点困难,所以我们想到可以枚举二分最终的数字~过程如下:
我们选到一个数字k,将其设定为结果,然后得到该数字在原数组中排第k大能否满足区间的数量,
如果大于m,我们就将k增大,反之减小;
尺取法判断(类似莫队的做法,见代码)
这里解释下其中代码的n-j+1的原因,我们首先已经找到了k个数字大于等于x,那么不管后面是否有大于x的数字,最多的区间可能就是n-j+1个(后面数字都小于等于x),这样我们算出来的就是x的理想最大区间数,如果此时还小于m,说明x一定是偏大了,就增大x的数值,反之则让二分区间为[l,mid],而不是[l,mid-1],因为mid这一点还无法准确判断,但是我们可以不断的二分判断出来,如果mid+1这点不满足大于m,那么就是mid这个点了,所以我们用ans每次保存了点,最后输出的就是答案(一定要多想想,很妙的做法的!)
#include<bits/stdc++.h>