跳到正文

个人记录

AtCoder - abc306_e

Chthohepta约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月23日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v1当前

题意

有长度为 nn 的序列 aa ,最初所有项都为 00。

每次将 axia_{x_i} 修改为 yiy_i ,并输出前 kk 大的数的和。

思路

我们可以使用 multiset 维护。

将 aa 分为前 kk 大和剩下 n−kn-k 个, 每次修改后将 aa 重新分类,将两类数中可交换的数交换。

代码

C++
#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;
}
原文