HDU - 2665 Kth number (主席树求区间第K小数模板题)

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

代码:

#include <cstdio>
#include <algorithm>

using namespace std;

const int MAXN = 1e5+10;

struct T{
	int L,R;
	int sum;
	T(){
		sum = 0;
	}
}Tree[MAXN*20];//这类题尽量开大点,否则很容易RE,甚至可能T。

struct V{
	int value,id;
	bool operator < (const struct V &b)const{
		return value < b.value;
	}
}board[MAXN];

int root[MAXN];
int Rank[MAXN];
int tot;

void Updata(int num,int &rt,int left,int right){
	Tree[++tot] = Tree[rt];
	rt = tot;
	Tree[rt].sum++;
	if(left == right)return ;
	int mid = left + (right-left)/2;
	if(num <= mid)Updata(num,Tree[rt].L,left,mid);
	else Updata(num,Tree[rt].R,mid+1,right);
}

int Query(int ql,int qr,int k,int left,int right){
	int t = Tree[Tree[qr].L].sum - Tree[Tree[ql].L].sum;
	if(left == right)return left;
	int mid = left + (right-left)/2;
	if(k <= t)return Query(Tree[ql].L,Tree[qr].L,k,left,mid);
	else return Query(Tree[ql].R,Tree[qr].R,k-t,mid+1,right);
}

inline void init(){
	tot = 0;
	root[0] = 0;
	Tree[0].L = Tree[0].R = Tree[0].sum = 0;
}

int main(){
	
	int T;
	scanf("%d",&T);
	int N,M;
	while(T--){
		scanf("%d %d",&N,&M);
		init();
		for(int i=1 ; i<=N ; ++i){
			scanf("%d",&board[i].value);
			board[i].id = i;
		}
		sort(board+1,board+1+N);
		for(int i=1 ; i<=N ; ++i)Rank[board[i].id] = i;
		for(int i=1 ; i<=N ; ++i){
			root[i] = root[i-1];
			Updata(Rank[i],root[i],1,N);
		}
		int left,right,k;
		for(int i=1 ; i<=M ; ++i){
			scanf("%d %d %d",&left,&right,&k);
			printf("%d\n",board[Query(root[left-1],root[right],k,1,N)].value);
		}
	}
	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值