結果

問題 No.3298 K-th Slime
コンテスト
ユーザー D M
提出日時 2026-01-15 10:20:53
言語 C++23
(gcc 15.2.0 + boost 1.89.0)
結果
AC  
実行時間 102 ms / 2,000 ms
コード長 2,013 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 3,956 ms
コンパイル使用メモリ 345,448 KB
実行使用メモリ 11,136 KB
最終ジャッジ日時 2026-01-15 10:21:00
合計ジャッジ時間 6,257 ms
ジャッジサーバーID
(参考情報)
judge2 / judge6
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 25
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    ll n, k, q;
    cin >> n >> k >> q;

    vector<ll> a(n);
    for (ll i = 0; i < n; i++) cin >> a[i];
    sort(a.begin(), a.end());

    multiset<ll> low, high; // low: k smallest, high: the rest
    for (ll i = 0; i < n; i++) {
        if (i < k) low.insert(a[i]);
        else high.insert(a[i]);
    }

    auto rebalance = [&]() {
        // size invariant
        while ((ll)low.size() > k) {
            auto it = prev(low.end());
            high.insert(*it);
            low.erase(it);
        }
        while ((ll)low.size() < k) {
            auto it = high.begin();
            low.insert(*it);
            high.erase(it);
        }
        // order invariant
        while (!low.empty() && !high.empty() && *prev(low.end()) > *high.begin()) {
            auto itL = prev(low.end());
            auto itH = high.begin();
            ll x = *itL, y = *itH;
            low.erase(itL);
            high.erase(itH);
            low.insert(y);
            high.insert(x);
        }
    };

    auto add_value = [&](ll x) {
        // low is supposed to have size k most of the time
        if (low.empty()) {
            low.insert(x);
        } else {
            ll kth = *prev(low.end());
            if ((ll)low.size() < k || x <= kth) low.insert(x);
            else high.insert(x);
        }
        rebalance();
    };

    while (q--) {
        ll c;
        cin >> c;
        if (c == 1) {
            ll x;
            cin >> x;
            add_value(x);
        } else if (c == 2) {
            ll y;
            cin >> y;
            auto it = prev(low.end());     // k-th smallest
            ll v = *it;
            low.erase(it);                 // remove k-th
            add_value(v + y);              // insert updated value
        } else { // c == 3
            cout << *prev(low.end()) << "\n"; // k-th smallest
        }
    }
    return 0;
}
0