为什么离散化就挂了?
代码如下:
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 200005;
int a[N], b[N];
struct Node {
int l, r, sum;
int lc, rc;
} node[N << 5];
int nodecnt;
int build(int l, int r) {
int p = ++ nodecnt;
node[p].l = l;
node[p].r = r;
node[p].sum = 0;
if (l != r) {
int mid = (l + r) / 2;
node[p].lc = build(l, mid);
node[p].rc = build(mid + 1, r);
}
return p;
}
int add(int p, int x) {
int newp = ++ nodecnt;
node[newp].l = node[p].l;
node[newp].r = node[p].r;
node[newp].sum = node[p].sum + 1;
if (node[p].l != node[p].r) {
int mid = (node[p].l + node[p].r) / 2;
if (x <= mid) {
node[newp].lc = add(node[p].lc, x);
node[newp].rc = node[p].rc;
} else {
node[newp].lc = node[p].lc;
node[newp].rc = add(node[p].rc, x);
}
}
return newp;
}
int query(int p1, int p2, int k) {
if (node[p1].l == node[p1].r) {
return node[p1].l;
} else {
int x = node[node[p2].lc].sum - node[node[p1].lc].sum;
if (k <= x) {
return query(node[p1].lc, node[p2].lc, k);
} else {
return query(node[p1].rc, node[p2].rc, k - x);
}
}
}
int rt[N];
int main() {
int n, q;
scanf("%d %d", &n, &q);
for (int i = 1; i <= n; i ++) {
scanf("%d", a + i);
b[i] = a[i];
}
sort(b + 1, b + n + 1);
int m = n;//unique(b + 1, b + n + 1) - (b + 1);
rt[0] = build(1, m);
for (int i = 1; i <= n; i ++) {
a[i] = lower_bound(b + 1, b + n + 1, a[i]) - b;
rt[i] = add(rt[i - 1], a[i]);
}
for (int l, r, k, i = 1; i <= q; i++) {
scanf("%d %d %d", &l, &r, &k);
printf("%d\n", b[query(rt[l - 1], rt[r], k)]);
}
return 0;
}