Processing math: 100%

HDU2665 Kth number 线段树 归并树

戳我进HDU原题

Kth number

Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

 

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,m100000) ,
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

HDU男生专场公开赛——赶在女生之前先过节(From WHU)
 

Recommend

zty
 

题目大意

  • 求区间第 k 大 无修改 n,m100000

 

思路

  • (好吧这确实是主席树or划分树的裸题)

  • 直接用线段树的思路:

  • 线段树 每个节点上 vector 保存当前区间已经排序好的序列

  • (归并一下就好了嘛 复杂度 O(n) 的)
    这样建树的时空复杂度都是 O(n×logn)

  • 对于每次询问 二分一个答案
    在树上 upperbound 一下 判断一下

  • 这样 查询的复杂度 就成 O(m×loginf×logn×logn) 的了

代码

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
#define N 100005
vector<int>sum[N<<2];
int T,n,m;
void build(int o,int l,int r){
	if(l==r){
		int val;
		scanf("%d",&val);
		sum[o].clear();
		sum[o].push_back(val);
		return;
	}
	int mid=l+r>>1;
	build(o<<1,l,mid); build(o<<1|1,mid+1,r);
	sum[o].resize(r-l+1);
	merge(sum[o<<1].begin(),sum[o<<1].end(),sum[o<<1|1].begin(),sum[o<<1|1].end(),sum[o].begin());
}
int query(int o,int l,int r,int L,int R,int val){
	if(L<=l&&r<=R) return upper_bound(sum[o].begin(),sum[o].end(),val)-sum[o].begin();
	int mid=l+r>>1;
	if(L>mid) return query(o<<1|1,mid+1,r,L,R,val);
	else if(R<=mid) return query(o<<1,l,mid,L,R,val);
	else return query(o<<1,l,mid,L,R,val)+query(o<<1|1,mid+1,r,L,R,val);
}
signed main(){
	scanf("%d",&T);
	while(T--){
		scanf("%d %d",&n,&m);
		build(1,1,n);
		while(m--){
			int l=0,r=n-1,k,L,R,ans;
			scanf("%d %d %d",&L,&R,&k);
			while(l<=r){
				int mid=l+r>>1;
				if(query(1,1,n,L,R,sum[1][mid])>=k){ ans=mid; r=mid-1; }
				else l=mid+1;
			}
			printf("%d\n",sum[1][ans]);
		}
	}
	return 0;
}
/*
Run ID        26214786
Submit Time   2018-09-07 20:30:15
Judge Status  Accepted
Pro.ID        2665
Exe.Time      4118MS
Exe.Memory    15824K
Code Len.     1169 B
Language      C++
Author        PotremZ
*/
posted @   potrem  阅读(356)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示