动态开点主席树
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, inf = 1e9;
int n, m, a[N], root[N], idx;
struct Node {
int l, r, cnt;
}tr[N << 5];
void insert(int &q, int p, int l, int r, int x) {
q = ++ idx;
tr[q] = tr[p];
tr[q].cnt ++;
if (l == r) return;
int mid = l + r >> 1;
if (x <= mid) insert(tr[q].l, tr[p].l, l, mid, x);
else insert(tr[q].r, tr[p].r, mid + 1, r, x);
}
int query(int p, int q, int l, int r, int k) {
if (l == r) return l;
int cnt = tr[tr[q].l].cnt - tr[tr[p].l].cnt;
int mid = l + r >> 1;
if (cnt >= k) return query(tr[p].l, tr[q].l, l, mid, k);
return query(tr[p].r, tr[q].r, mid + 1, r, k - cnt);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) {
cin >> a[i];
insert(root[i], root[i - 1], -inf, inf, a[i]);
}
int l, r, k;
for (int i = 0; i < m; i ++ ) {
cin >> l >> r >> k;
cout << query(root[l - 1], root[r], -inf, inf, k) << endl;
}
return 0;
}