题意:https://www.luogu.org/problem/P2617
动态区间第 K 大
考虑把修改记为删除原数和添加新数的操作,之后就与静态区间第 K 大无异
这时可能有疑问:时间的影响呢?
由于我们的操作序列初始时是以时间排序的,在处理时枚举也是从左往右,那么每次二分处理的操作序列也是以时间排序的,在询问前的操作一定都进行了,所以不会wrong
code:
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 2e5 + 5;
int n, m, cnt, tot;
int a[maxn], tree[maxn], ans[maxn];
int lowbit(int x) {
return x & -x;
}
struct node {
int l, r, k, id, op;
} q[maxn*3], q1[maxn*3], q2[maxn*3];
void add(int x, int k) {
while (x <= n) {
tree[x] += k;
x += lowbit(x);
}
}
int query(int x) {
int res = 0;
while (x) {
res += tree[x];
x -= lowbit(x);
}
return res;
}
void solve(int l, int r, int L, int R) {
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, cnt1 = 0, cnt2 = 0;
for (int i = L; i <= R; i++) {
if (q[i].op == 1) {
if (q[i].l <= mid) q1[++cnt1] = q[i], add(q[i].id, q[i].r);
else q2[++cnt2] = q[i];
} else {
int x = query(q[i].r) - query(q[i].l - 1);
if (q[i].k <= x) q1[++cnt1] = q[i];
else q[i].k -= x, q2[++cnt2] = q[i];
}
}
for (int i = 1; i <= cnt1; i++) if (q1[i].op == 1) add(q1[i].id, -q1[i].r);
for (int i = 1; i <= cnt1; i++) q[L+i-1] = q1[i];
for (int i = 1; i <= cnt2; i++) q[L+cnt1+i-1] = q2[i];
solve(l, mid, L, L+cnt1-1);
solve(mid+1, r, L+cnt1, R);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
q[++cnt] = (node){a[i], 1, 0, i, 1};
}
for (int i = 1; i <= m; i++) {
char op;
cin >> op;
if (op == 'Q') {
int l, r, k;
cin >> l >> r >> k;
q[++cnt] = (node){l, r, k, ++tot, 2};
} else {
int x, y;
cin >> x >> y;
q[++cnt] = (node){a[x], -1, 0, x, 1};
q[++cnt] = (node){a[x]=y, 1, 0, x, 1};
}
}
solve(-INF, INF, 1, cnt);
for (int i = 1; i <= tot; i++) {
cout << ans[i] << '\n';
}
return 0;
}