主席数

HDU 2665 Kth number


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

题意:给n个数的数组,m次询问,每次询问区间【L,R】的第k小
做法:裸的主席树,按点的位置,依次加入点权,每次询问,访问历史版本L和R二分判断答案即可。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
#define N 100005
int root[N], size[N*20], lchild[N*20], rchild[N*20];
int tot;
int a[N], b[N];	
map<int, int>mp;
void insert(int last, int cur, int L, int R, int k)
{
	size[cur]=size[last];
	lchild[cur]=lchild[last];
	rchild[cur]=rchild[last];
	if(L==R)
	{
		size[cur]++;
		return;
	}
	int mid=L+R>>1;
	if(k<=mid) insert(lchild[last], lchild[cur]=++tot, L, mid, k);
	else insert(rchild[last], rchild[cur]=++tot, mid+1, R, k);
	size[cur]=size[lchild[cur]]+size[rchild[cur]];
}

int query(int last, int cur, int k, int L, int R)
{
	if(L==R) return L;
	int mid=L+R>>1;
	int nows=size[lchild[cur]]-size[lchild[last]];
	if(nows>=k) return query(lchild[last], lchild[cur], k, L, mid);
	else return query(rchild[last], rchild[cur], k-nows, mid+1, R);
}
int main()
{
	int t;
	scanf("%d", &t);
	while(t--)
	{
		tot=0;
		int ss=0, n, m, i, at;
		scanf("%d%d", &n, &m);
		for(i = 1; i <= n; i++)
		{	
			scanf("%d", &a[i]);
			b[i]=a[i];
		}
		sort(b+1, b+n+1);
		at = unique(b+1, b+n+1)-b;
		at--;
		for(i = 1; i <= at; i++) mp[b[i]]=++ss;
		//cout<<"**"<<endl;
		for(i = 1; i <= n; i++)
		{
			root[i]=++tot;
			insert(root[i-1], root[i], 1, at, mp[a[i]]);
		}
		for(i = 0; i < m; i++)
		{
			int l, r, k;
			scanf("%d%d%d", &l, &r, &k);
			printf("%d\n", b[query(root[l-1], root[r], k, 1, at)]);
		}
	}
	return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值