题意
有长度为 的序列 ,最初所有项都为 。
每次将 修改为 ,并输出前 大的数的和。
思路
我们可以使用 multiset 维护。
将 分为前 大和剩下 个, 每次修改后将 重新分类,将两类数中可交换的数交换。
代码
#include <bits/stdc++.h>
#define ll long long
#define min(a, b) (a < b ? a : b)
#define max(a, b) (a > b ? a : b)
using namespace std;
ll read(){ ll x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-'){ f = -1; } ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0', ch = getchar(); } return x * f; }
void write(ll x) { if(x < 0){ putchar('-'), x = -x; } if(x > 9){ write(x / 10); } putchar(x % 10 + '0'); return; }
const int N = 5e5 + 3;
int n, k, q;
ll x, y, yy;
ll a[N];
multiset <ll> st1, st2;
ll s1, s2;
ll ans;
int main(){
n = read(), k = read(), q = read();
for(int i = 1; i <= k; i ++){
st1.insert(0);
}
for(int i = k + 1; i <= n; i ++){
st2.insert(0);
}
while(q --){
x = read(), y = read();
if(st1.find(a[x]) != st1.end()){
st1.erase(st1.find(a[x]));
st1.insert(y);
ans += -a[x] + y;
}
else{
st2.erase(st2.find(a[x]));
st2.insert(y);
}
while(!st2.empty() && (*st1.begin()) < (*st2.rbegin())){
ans += (*st2.rbegin()) - (*st1.begin());
s1 = (*st1.begin()), s2 = (*st2.rbegin());
st1.erase(st1.find(s1)), st1.insert(s2);
st2.erase(st2.find(s2)), st2.insert(s1);
}
write(ans), putchar('\n');
a[x] = y;
}
return 0;
}