HDU2665-Kth number

本文介绍了一种解决区间内查找第K大数的问题的方法。通过预先排序和重新编号,利用可持久化线段树进行高效维护和查询。适用于大规模数据集,提供了一个完整的C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Kth number

                                                                      Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
                                                                                                    Total Submission(s): 9899    Accepted Submission(s): 3070


Problem Description
Give you a sequence and ask you the kth big number of a inteval.
 

Input
The first line is the number of the test cases. 
For each test case, the first line contain two integer n and m (n, m <= 100000), indicates the number of integers in the sequence and the number of the quaere. 
The second line contains n integers, describe the sequence. 
Each of following m lines contains three integers s, t, k. 
[s, t] indicates the interval and k indicates the kth big number in interval [s, t]
 

Output
For each test case, output m lines. Each line contains the kth big number.
 

Sample Input
  
1 10 1 1 4 2 3 5 6 7 8 9 0 1 3 2
 

Sample Output
  
2
 

Source

题意:给出n个数,有m个询问,求区间内第k大的数是哪个

解题思路:由于题目未说明n个数的范围,因此可以先做一个预处理,将n个数排序后重新编号,然后建一棵可持久化线段树来维护


#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <bitset>
#include <set>
#include <vector>
#include <functional>

using namespace std;

#define LL long long
const int INF = 0x3f3f3f3f;

int n, q,m;
int a[100009], b[100009],tot;
int L[100009 * 20], R[100009 * 20], s[100009], sum[100009 * 20];

void build(int pre,int &now, int l, int r, int k)
{
	sum[now=++tot] = sum[pre] + 1;
	if (l == r) { L[now] = R[now] = 0; return; }
	int mid = (l + r) >> 1;
	L[now] = L[pre], R[now] = R[pre];
	if (mid >= k) build(L[pre],L[now], l, mid, k);
	else build(R[pre],R[now], mid + 1, r, k);
}

int query(int k, int kk, int l, int r, int p)
{
	if (l == r) return l;
	int mid = (l + r) >> 1;
	if (p > sum[L[k]] - sum[L[kk]]) return query(R[k], R[kk], mid + 1, r, p - sum[L[k]] + sum[L[kk]]);
	else return query(L[k], L[kk], l, mid, p);
}

int main()
{
	while (~scanf("%d%d", &n,&q))
	{
		for (int i = 1; i <= n; i++) scanf("%d", &a[i]), b[i] = a[i];
		sort(b + 1, b + 1 + n);
		m = unique(b + 1, b + 1 + n) - b;
		L[0] = R[0] = sum[0] = tot =s[0]= 0;
		for (int i = 1; i <= n; i++)
		{
			a[i] = lower_bound(b + 1, b + m, a[i]) - b;
			build(s[i - 1],s[i], 1, m, a[i]);
		}
		while (q--)
		{
			int l, r, k;
			scanf("%d%d%d", &l, &r, &k);
			printf("%d\n", b[query(s[r], s[l-1], 1, m, k)]);
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值