HDU2665 Kth Number (主席树+离散)模板

Kth number

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


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
 

卿姐视频:点击打开链接

/*
题目意思:求第k"大"的数

思路:(主席树模板+离散化)
	1. 输入去重
	2.每个点形成一个历史版本的主席树
	3. 进行区间查询,前缀和 
*/

#include<bits/stdc++.h>

using namespace std;
const int maxn = 1e6+10;
int a[maxn],cnt;
int root[maxn];
vector<int> v;

struct node{
	int l,r,sum;
}T[maxn*25];

int getid(int x){
	//return 第一个大于等于的值 
	return lower_bound(v.begin(),v.end(),x)-v.begin()+1;
}

//2.生成线段树 
void update(int l,int r,int &x,int y,int pos){
	T[++cnt]=T[y];
	T[cnt].sum++;
	x=cnt;						//修改root[i]所指的根节点 
	if(l==r) return ;   		//更新完成
	int mid = (l+r)>>1;
	//在左子树 
	if(mid >= pos) update(l,mid,T[x].l,T[y].l,pos);  
	else update(mid+1 ,r ,T[x].r,T[y].r,pos);
}

int query(int l, int r,int x, int y,int val){
	if(l==r) return l;			//查询成功 
	int mid = (l+r)>>1;		
	int sum = T[T[y].l].sum - T[T[x].l].sum;
	if(sum >= val ) return query(l,mid,T[x].l,T[y].l,val);
	else return query(mid+1 ,r ,T[x].r,T[y].r,val-sum);
}

int main(){
	int t,n,m,l,r,p;
	scanf("%d",&t);
	while(t--){
		cnt=0;
		v.clear();
		scanf("%d%d",&n,&m);
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
			v.push_back(a[i]);
		}
		//1.去重 
		sort(v.begin(),v.end());
		v.erase(unique(v.begin(),v.end()),v.end());
		
		for(int i=1;i<=n;i++) update(1,n,root[i],root[i-1],getid(a[i]));
		for(int i=1;i<=m;i++){
			scanf("%d%d%d",&l,&r,&p);
			printf("%d\n",v[query(1,n,root[l-1],root[r],p)-1]);
		} 
	}
} 

猜你喜欢

转载自blog.csdn.net/rvelamen/article/details/80732915
今日推荐