K-th number
求区间内第k小的数。主席树的板子题
主席树左子树存小值,右边大值,用sum记录一下子树节点个数。对(l,r)的查询区间,root【r】 - root【l- 1】可得出(l,r)的差值,也就是大小的个数
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <ctype.h>
#include <bitset>
#define LL long long
#define ULL unsigned long long
#define mod 10007
#define INF 0x7ffffff
#define mem(a,b) memset(a,b,sizeof(a))
#define MODD(a,b) (((a%b)+b)%b)
#define lson rt << 1
#define rson rt << 1 | 1
using namespace std;
const int maxn = 2e5 + 5;
int a[maxn];
int root[maxn];
int cnt = 0;
struct node
{
int l,r,sum;
}hjt[maxn*40];
vector<int> V;
int getId(int x)
{
return lower_bound(V.begin(),V.end(),x) - V.begin() + 1;
}
void upDate(int l,int r,int pre,int &now,int p)
{
hjt[++cnt] = hjt[pre];
now = cnt;
hjt[now].sum++;
if(l == r) return;
int mid = (l + r) >> 1;
if(p <= mid) upDate(l,mid,hjt[pre].l,hjt[now].l,p);
else upDate(mid + 1,r,hjt[pre].r,hjt[now].r,p);
}
int query(int l,int r,int L,int R,int k)
{
if(l == r) return l;
int tmp = hjt[hjt[R].l].sum - hjt[hjt[L].l].sum;
int mid = (l + r) >> 1;
if(k <= tmp) return query(l,mid,hjt[L].l,hjt[R].l,k);
else return query(mid + 1,r,hjt[L].r,hjt[R].r,k - tmp);
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
int n,m;
scanf("%d%d",&n,&m);
cnt = 0;
for(int i = 1; i <= n; i++){
scanf("%d",&a[i]);
V.push_back(a[i]);
}
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 - 1],root[i],getId(a[i]));
}
while(m--){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
printf("%d\n",V[query(1,n,root[x - 1],root[y],z) - 1]);
}
V.clear();
mem(a,0),mem(root,0);
}
return 0;
}