Kth number(HDU2665)

本文介绍如何使用主席树解决区间第k大问题,通过实例讲解了主席树的构建和查询过程,包括节点数量存储、链更新及查询算法。

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

题目

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

翻译一下啦~:
给你一个序列,然后问你第k个大数。

输入
第一行是测试用例的数量。对于每个测试用例,第一行包含两个整数n和m(n,m <= 100000),表示序列中的整数数和quaere数。第二行包含n个整数,描述序列。以下m行中的每一行包含三个整数s,t,k。[s,t]表示间隔,k表示区间[s,t]中的第k个大数

输出
对于每个测试用例,输出m行。 每行包含第k个大数字。

思路:一道很经典的主席树入门啦,就是求区间第k大,这里我讲的不是很清楚,可以看看这位大佬讲的 浅谈主席树,然后谈谈我的看法

主席树,首先每个点存的是这个区间的节点数量,一棵树是由很多条链构成,我们每次插入一个新的节点,只需要修改一条链就可以了,这样大大减少了空间的同时也在更新这棵树,然后我们查询的时候,是利用每个数据所在的根节点,比较不同区间的节点数量得到结果~
(因为第一次没有用结构体写树,一开始十分生疏~)

代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int mx=2e6+10;
int ls[mx],rs[mx],rt[mx],sum[mx];//分别代表着左儿子,右儿子,数据所在链,区间节点数量
int a[mx],b[mx],tot;//分别为输入的数据,离散化操作之后的,以及总结点数量

void update(int &now,int pre,int l,int r,int k)//新建一条链
{
	now=++tot;//编号加1
	ls[now]=ls[pre];//首先继承父亲的
	rs[now]=rs[pre];
	sum[now]=sum[pre]+1;//记得数量加1
	if(l==r) return;
	int mid=l+r>>1;
	if(k<=mid)
	update(ls[now],ls[pre],l,mid,k);
	else
	update(rs[now],rs[pre],mid+1,r,k);
}

int query(int now,int pre,int l,int r,int k)//查询过程
{
	if(l==r) return l;
	int mid=(l+r)>>1;
	int  cnt=sum[ls[now]]-sum[ls[pre]];//比较区间的左边数量和k的大小
	if(k<=cnt)//因为[l,r]区间的左边数量为[1,r]-[1,l]的左儿子数量
	return query(ls[now],ls[pre],l,mid,k);
	else
	return query(rs[now],rs[pre],mid+1,r,k-cnt);
}

int main()
{
	int n,m,t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m);
		sum[0]=rt[0]=ls[0]=rs[0]=tot=0;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			b[i]=a[i];
		}
		sort(b+1,b+1+n);//排序
		int  len=unique(b+1,b+1+n)-(b+1);//去重得到长度
		for(int i=1;i<=n;i++)
		a[i]=lower_bound(b+1,b+1+len,a[i])-b;//然后得到a[i]所在的第几个位置
		for(int i=1;i<=n;i++)
		update(rt[i],rt[i-1],1,len,a[i]);//更新,利用上一条链
		for(int i=1;i<=m;i++)
		{
		   int x,y,z,ans;
		   scanf("%d%d%d",&x,&y,&z);
		   ans=query(rt[y],rt[x-1],1,len,z);//查询嘛,记得x-1;
		   printf("%d\n",b[ans]);//因为[x,y]=[1,y]-[1,x-1];
	    }
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值