题目链接:K大数查询
大致题意
QAQ如题面所述
解题思路
我们需要实现的操作有三种: 区间修改, 区间查询, 查询区间第K大.
然后一想, 可以树套树(推荐线段树+线段树), 然后我就一直错最后一个测试用例QAQ, 也不知道为什么.
再转念一想, 我最近不是学了个整体二分, 查询第K大可以整体二分, 那么维护前面的区间操作可以采用线段树做维护.
AC代码
//整体二分代码
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 5E4 + 10, INF = 0x3f3f3f3f;
int res[N];
struct operation {
int t, l, r; ll c; int id;
}; vector<operation> area;
struct node {
int l, r;
ll val;
ll lazy;
}t[N << 2];
void pushdown(node& op, ll lazy) {
op.val += (op.r - op.l + 1) * lazy;
op.lazy += lazy;
}
void pushdown(int x) {
if (!t[x].lazy) return;
pushdown(t[x << 1], t[x].lazy), pushdown(t[x << 1 | 1], t[x].lazy);
t[x].lazy = 0;
}
void pushup(int x) { t[x].val = t[x << 1].val + t[x << 1 | 1].val; }
void build(int l, int r, int x = 1) {
t[x] = { l, r, 0, 0 };
if (l == r) return;
int mid = l + r >> 1;
build(l, mid, x << 1), build(mid + 1, r, x << 1 | 1);
}
void modify(int l, int r, int c, int x = 1) {
if (l <= t[x].l && r >= t[x].r) {
pushdown(t[x], c);
return;
}
pushdown(x);
int mid = t[x].l + t[x].r >> 1;
if (l <= mid) modify(l, r, c, x << 1);
if (r > mid) modify(l, r, c, x << 1 | 1);
pushup(x);
}
ll ask(int l, int r, int x = 1) {
if (l <= t[x].l && r >= t[x].r) return t[x].val;
pushdown(x);
int mid = t[x].l + t[x].r >> 1;
int res = 0;
if (l <= mid) res += ask(l, r, x << 1);
if (r > mid) res += ask(l, r, x << 1 | 1);
return res;
}
void fact(int l, int r, vector<operation>& q) {
if (q.empty()) return;
if (l == r) {
for (auto& op : q) if (op.t == 2) res[op.id] = l;
return;
}
int mid = l + r >> 1;
vector<operation> ql, qr;
for (auto& op : q) {
if (op.t == 1) {
if (op.c > mid) modify(op.l, op.r, 1), qr.push_back(op);
else ql.push_back(op);
}
else {
ll cou = ask(op.l, op.r);
if (cou >= op.c) qr.push_back(op);
else op.c -= cou, ql.push_back(op);
}
}
for (auto& op : qr) if (op.t == 1) modify(op.l, op.r, -1);
fact(l, mid, ql), fact(mid + 1, r, qr);
}
int main()
{
int n, m; cin >> n >> m;
rep(i, m) {
res[i] = INF;
int k, a, b, c; scanf("%d %d %d %d", &k, &a, &b, &c);
area.push_back({ k, a, b, c, i });
}
build(1, n);
fact(-n, n, area);
rep(i, m) if (res[i] != INF) printf("%d\n", res[i]);
return 0;
}