查询区间第 K K K 小
题目连接:luogu P3834主席树模板题
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn = 2e5 + 10;
struct node{
int l, r; //左右子节点的编号,不再用层次序编号
int sum; //记录值域区间[L,R]中一共插入过多少个数
}tree[maxn * 40]; //开40倍的空间
int cnt, root[maxn]; //可持久化线段树的总点数和每个根
int n, m;
int a[maxn], b[maxn];
void init(){
cnt = 0;
}
int build(int l, int r){ //初始化,sum全是0
int p = ++cnt;
tree[p].sum = 0;
if(l == r) return p;
int mid = (l + r) / 2;
tree[p].l = build(l, mid);
tree[p].r = build(mid+1, r);
return p;
}
int insert(int pre, int l, int r, int x){
int p = ++cnt;
tree[p] = tree[pre];
tree[p].sum++;
if(l == r) return p;
int mid = (l + r) / 2;
if(x <= mid) tree[p].l = insert(tree[pre].l, l, mid, x);
else tree[p].r = insert(tree[pre].r, mid+1, r, x);
return p;
}
//在p, q两个根节点上,值域为[l, r], 求第k小数
int query(int p,int q,int l,int r,int k){
if(l == r) return l;
int mid = (l + r) / 2;
//有多少个数落在值域[l, mid]内
int sum = tree[tree[p].l].sum - tree[tree[q].l].sum;
if(k <= sum) return query(tree[p].l, tree[q].l, l, mid, k);
else return query(tree[p].r, tree[q].r, mid+1, r, k - sum);
}
int main()
{
cin>>n>>m;
for(int i = 1; i <= n; i++){
cin>>a[i];
b[i] = a[i];
}
sort(b+1, b+1+n); //离散化
int size = unique(b+1, b+1+n)-b-1;
init();
root[0] = build(1, size);
for(int i = 1; i <= n; i++)
root[i] = insert(root[i-1],1,size,lower_bound(b+1,b+size+1,a[i])-b);
int l, r, k;
while(m--){
scanf("%d%d%d",&l,&r,&k);
cout<<b[query(root[r], root[l-1], 1, size, k)]<<endl;
}
return 0;
}