原题链接
主席树,本题在查询前可以不用建树,每个版本加log(2e9)个节点,空间复杂度不会超过1e5 * log(2e9) 不会超过1e5 * 32,可以不用离散化直接做。
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 100010;
struct Node {
int l, r, s;
}tr[N * 32];
int n, m, idx, a[N], root[N];
int ins(int v, int l, int r, int k, int x) {
int u = ++ idx;
tr[u] = tr[v];
tr[u].s ++;
if (l == r) return u;
LL mid = l * 1ll + r >> 1;
if (k <= mid) tr[u].l = ins(tr[v].l, l, mid, k, x);
else tr[u].r = ins(tr[v].r, mid + 1, r, k, x);
return u;
}
int query(int v, int u, int l, int r, int k) {
if (l == r) return l;
LL mid = l * 1ll + r >> 1;
if (k <= tr[tr[u].l].s - tr[tr[v].l].s) return query(tr[v].l, tr[u].l, l, mid, k);
else return query(tr[v].r, tr[u].r, mid + 1, r, k - (tr[tr[u].l].s - tr[tr[v].l].s));
}
int main() {
cin >> n >> m;
idx = 0;
for (int i = 1; i <= n; i ++) {
int x;
cin >> x;
root[i] = ins(root[i - 1], -1e9, 1e9, x, 1);
}
while (m --) {
int l, r, x;
cin >> l >> r >> x;
cout << query(root[l - 1], root[r], -1e9, 1e9, x) << endl;
}
return 0;
}