Kth number
思路:
可持久化线段树(主席树)模板题。(点我学习)
代码:
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
int t, n, m, tot;
int ls[maxn*20], rs[maxn*20], sum[maxn*20], rt[maxn], sorted[maxn], num[maxn];
void build(int l, int r, int &rt){
rt = ++tot;
sum[rt] = 0;
if(l==r){
return ;
}
int mid = l + r >> 1;
build(l, mid, ls[rt]);
build(mid+1, r, rs[rt]);
}
void update(int pos, int l, int r, int &rt, int last){
rt = ++tot;
ls[rt] = ls[last];
rs[rt] = rs[last];
sum[rt] = sum[last] + 1;
if(l==r){
return ;
}
int mid = l + r >> 1;
if(pos<=mid){
update(pos, l, mid, ls[rt], ls[last]);
}
else {
update(pos, mid+1, r, rs[rt], rs[last]);
}
}
int query(int L, int R, int l, int r, int k){
if(l==r){
return l;
}
int mid = l + r >> 1;
int cnt = sum[ls[R]] - sum[ls[L]];
if(k <= cnt){
return query(ls[L], ls[R], l, mid, k);
}
else{
return query(rs[L], rs[R], mid+1, r, k-cnt);
}
}
int main(){
int l, r, k;
scanf("%d", &t);
while(t--){
tot = 0;
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; ++i){
scanf("%d", &sorted[i]);
num[i] = sorted[i];
}
sort(sorted+1, sorted+n+1);
int cnt = unique(sorted+1, sorted+n+1) - sorted - 1;
build(1, cnt, rt[0]);
for(int i = 1; i <= n; ++i){
num[i] = lower_bound(sorted+1, sorted+cnt+1, num[i]) - sorted;
}
for(int i = 1; i <= n; ++i){
update(num[i], 1, cnt, rt[i], rt[i-1]);
}
for(int i = 1; i <= m; ++i){
scanf("%d %d %d", &l, &r, &k);
printf("%d\n", sorted[query(rt[l-1], rt[r], 1, cnt, k)]);
}
}
return 0;
}