题意
传送门 P3834
题解
主席树裸题,考虑到未更新的节点代表的区间和为 0 0 0,可以省去建树这一步,用初始根节点的值映射未更新节点的值。
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
#define maxn 200005
#define tree_size 4000005
int N, M, cnt, A[maxn], B[maxn], rt[maxn];
int sum[tree_size], cl[tree_size], cr[tree_size];
int compress()
{
for (int i = 0; i < N; ++i)
B[i] = A[i];
sort(B, B + N);
int n = unique(B, B + N) - B;
for (int i = 0; i < N; ++i)
A[i] = lower_bound(B, B + n, A[i]) - B;
return n;
}
int update(int pre, int x, int l, int r)
{
int cur = ++cnt;
cl[cur] = cl[pre], cr[cur] = cr[pre], sum[cur] = sum[pre] + 1;
if (r - l > 1)
{
int m = (l + r) >> 1;
x < m ? cl[cur] = update(cl[pre], x, l, m) : cr[cur] = update(cr[pre], x, m, r);
}
return cur;
}
int query(int u, int v, int k, int l, int r)
{
if (r - l == 1)
return l;
int x = sum[cl[v]] - sum[cl[u]], m = (l + r) >> 1;
return k <= x ? query(cl[u], cl[v], k, l, m) : query(cr[u], cr[v], k - x, m, r);
}
int main()
{
scanf("%d%d", &N, &M);
for (int i = 0; i < N; ++i)
scanf("%d", A + i);
int n = compress();
for (int i = 0; i < N; ++i)
rt[i + 1] = update(rt[i], A[i], 0, n);
while (M--)
{
int l, r, k;
scanf("%d%d%d", &l, &r, &k);
printf("%d\n", B[query(rt[l - 1], rt[r], k, 0, n)]);
}
return 0;
}