hdu 6231 K-th Number(二分+尺取)

K-th Number

Time Limit: 2000/1000 MS (Java/Others)
Memory Limit:262144/262144K(Java/Others)
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(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个数,第i个数为ai,从序列中取连续的一段数,将其中第k大的数加入集合b(如果不存在第k大的数则忽略),求集合b第m大的数。

题解:

二分答案,求区间第k大的数>=x的区间组合有多少个,如果大于等于m,更新左区间为mid,否则右区间更新为mid-1。对于求第k大数>=x的区间有多少个,可以使用尺取法,对于左区间为l,若到右区间r中>=mid的数大于等于k,则区间第k大数>=mid的区间组合共有n-r+1个(即左端点为l,右端点为[r,n]都可以,可以保证区间第k大的数>=mid)。

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<ctype.h>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<iostream>
#include<iterator>
#define dbg(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
#define eps 1e-8
 
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 100100;
const int mod = 998244353;
int a[maxn];
bool isok(int mid, int n, int k, LL m);

int main()
{
	int t, n, k, i, j, l, r;
	LL m;
	scanf("%d", &t);
	while(t--)
	{
		l = INF, r = 0;
		scanf("%d %d %lld", &n, &k, &m);
		for(i=0;i<n;i++){
			scanf("%d", &a[i]);
			r = max(r, a[i]);
			l = min(l, a[i]);
		}
		while(l<r)
		{
			int mid = (l+r+1)/2;
			if(isok(mid, n, k, m))
				l = mid;
			else
				r = mid-1;
		}
		printf("%d\n", l);
	}
	return 0;
}

bool isok(int mid, int n, int k, LL m)
{
	int num, l, r;
	LL sum = 0;
	num = l = r = 0;
	while(l<n)
	{
		while(r < n && num < k){
			if(a[r] >= mid)num++;
			r++;
		}
		//不能使第k大数>=mid,跳出,避免加到计数器中
		if(num < k)break;
		//实际上右区间取[r-1,n-1]都满足区间第k大>=mid
		sum += n - r + 1;
		if(a[l] >= mid)num--;
		l++;
	}
	return sum >= m;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值