题意
查询区间第 K K K大,不过是多个区间拼起来的区间。
思路
在普通区间第 K K K大的问题中,我们只是做了一个区间,因为这里小区间的个数很小,所以我们可以直接暴力统计。
代码
#include<cstdio>
#include<algorithm>
struct node {
int lc, rc, dat;
}tree[6000001];
int nn, n, m, kk, p, tot;
int a[200001], b[200001], root[200001], x[6], y[6];
int build(int l, int r) {
int p = ++tot;
if (l == r) return p;
int mid = (l + r) >> 1;
tree[p].lc = build(l, mid);
tree[p].rc = build(mid + 1, r);
return p;
}
int insert(int now, int l, int r, int x, int val) {
int p = ++tot;
tree[p] = tree[now];
if (l == r) {
tree[p].dat += val;
return p;
}
int mid = (l + r) >> 1;
if (x <= mid)
tree[p].lc = insert(tree[now].lc, l, mid, x, val);
else
tree[p].rc = insert(tree[now].rc, mid + 1, r, x, val);
tree[p].dat = tree[tree[p].lc].dat + tree[tree[p].rc].dat;
return p;
}
int ask(int p[], int q[], int l, int r, int k) {
if (l == r) return l;
int mid = (l + r) >> 1;
int lcnt = 0;
for (int i = 1; i <= kk; i++)
lcnt += tree[tree[p[i]].lc].dat - tree[tree[q[i]].lc].dat;//多个小区间
if (k <= lcnt) {
for (int i = 1; i <= kk; i++)
p[i] = tree[p[i]].lc, q[i] = tree[q[i]].lc;
return ask(p, q, l, mid, k);
} else {
for (int i = 1; i <= kk; i++)
p[i] = tree[p[i]].rc, q[i] = tree[q[i]].rc;
return ask(p, q, mid + 1, r, k - lcnt);
}
}
int main() {
scanf("%d %d", &nn, &m);
for (int i = 1; i <= nn; i++) {
scanf("%d", &a[i]);
b[i] = a[i];
}
std::sort(b + 1, b + nn + 1);
n = std::unique(b + 1, b + nn + 1) - b - 1;
root[0] = build(1, n);
for (int i = 1; i <= nn; i++) {
a[i] = std::lower_bound(b + 1, b + n + 1, a[i]) - b;
root[i] = insert(root[i - 1], 1, n, a[i], 1);
}
for (; m; m--) {
scanf("%d %d", &kk, &p);
for (int i = 1; i <= kk; i++)
scanf("%d %d", &x[i], &y[i]), x[i] = root[x[i] - 1], y[i] = root[y[i]];
printf("%d\n", b[ask(y, x, 1, n, p)]);
}
}