K大数查询
题目链接:ybt金牌导航6-6-3 / luogu P3332
题目大意
给你若干个集合,它们是可重集,一开始都是空集,然后有两种操作:
把连续一些位置的集合中都放入一个数,查询一些连续位置的集合的并集中第 x 大的数。
思路
这题首先发现每个询问你可以用二分来求。
那我们就考虑整体二分。
然后由于它是区间修改(之类的东西?),你就可以用一个线段树维护。
然后注意是第 k k k 大不是第 k k k 小,然后记得 long long 即可。
代码
#include<cstdio>
#include<iostream>
#define ll long long
using namespace std;
struct node {
ll op, l, r, c, tmp, id;
}q[50001], q1[50001], q2[50001];
int n, m, ans[50001], tot;
ll op, l, r, c;
ll tmp[50001];
struct XD_tree {//线段树维护区间加值和区间查询
ll a[50001 << 2], lzy[50001 << 2];
void up(int now) {
a[now] = a[now << 1] + a[now << 1 | 1];
}
void down(int now, int l, int r) {
if (!lzy[now]) return ;
int mid = (l + r) >> 1;
a[now << 1] += lzy[now] * (mid - l + 1);
a[now << 1 | 1] += lzy[now] * (r - mid);
lzy[now << 1] += lzy[now]; lzy[now << 1 | 1] += lzy[now];
lzy[now] = 0;
}
void insert(int now, int l, int r, int L, int R, ll va) {
if (L <= l && r <= R) {
a[now] += va * (r - l + 1);
lzy[now] += va;
return ;
}
down(now, l, r);
int mid = (l + r) >> 1;
if (L <= mid) insert(now << 1, l, mid, L, R, va);
if (mid < R) insert(now << 1 | 1, mid + 1, r, L, R, va);
up(now);
}
ll query(int now, int l, int r, int L, int R) {
if (L <= l && r <= R) return a[now];
down(now, l, r);
ll re = 0;
int mid = (l + r) >> 1;
if (L <= mid) re += query(now << 1, l, mid, L, R);
if (mid < R) re += query(now << 1 | 1, mid + 1, r, L, R);
return re;
}
}T;
void work(int l, int r, int L, int R) {//整体二分(是第k大不是第k小)
if (l > r) return ;
if (L == R) {
for (int i = l; i <= r; i++)
if (q[i].op == 2) ans[q[i].id] = L;
return ;
}
int mid = (L + R) >> 1;
int n1 = 0, n2 = 0;
for (int i = l; i <= r; i++) {
if (q[i].op == 1) {
if (q[i].c <= mid) q1[++n1] = q[i];
else T.insert(1, 1, n, q[i].l, q[i].r, 1), q2[++n2] = q[i];
}
else {
tmp[i] = T.query(1, 1, n, q[i].l, q[i].r);
if (tmp[i] + q[i].tmp >= q[i].c) {
q2[++n2] = q[i];
}
else q[i].tmp += tmp[i], q1[++n1] = q[i];
}
}
for (int i = l; i <= r; i++) {
if (q[i].op == 1 && q[i].c > mid) {
T.insert(1, 1, n, q[i].l, q[i].r, -1);
}
}
for (int i = 1; i <= n1; i++) q[l + i - 1] = q1[i];
for (int i = 1; i <= n2; i++) q[l + n1 + i - 1] = q2[i];
work(l, l + n1 - 1, L, mid); work(l + n1, r, mid + 1, R);
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%lld %lld %lld %lld", &op, &l, &r, &c);
q[i] = (node){op, l, r, c, 0, (op == 2) ? (++tot) : 0};
}
work(1, m, -n, n);
for (int i = 1; i <= tot; i++) printf("%d\n", ans[i]);
return 0;
}