結果

問題 No.3114 0→1
コンテスト
ユーザー Mistletoe
提出日時 2025-04-19 09:26:01
言語 C++17
(gcc 15.3.0 + boost 1.92.0 + ACL)
コンパイル:
g++-15 -O2 -lm -std=c++17 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
WJ  
(最新)
AC  
(最初)
実行時間 -
コード長 1,252 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
最終ジャッジ日時 2026-10-16 03:23:58
ジャッジサーバーID
(参考情報)
judge4_0 / judge3_0
このコードへのチャレンジ
(要ログイン)

ソースコード

diff #
raw source code

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

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

    int N;
    string S;
    cin >> N >> S;

    long long ps = 0;        // current prefix‐sum (1→+1, 0→–1, with flips applied on the fly)
    long long max_ps = 0;    // max prefix‐sum over positions ≤ i–2
    int flips = 0;           // total flips performed
    priority_queue<int> zeros;  // max‐heap of indices of kept zeros

    for (int i = 0; i < N; i++) {
        long long prev = ps;            // ps at position i–1

        if (S[i] == '1') {
            ps = prev + 1;
        } else {
            // tentatively keep this zero
            zeros.push(i);
            ps = prev - 1;

            // for i>=1 we must have ps(i) >= max_ps, else flip zeros
            if (i >= 1) {
                while (ps < max_ps) {
                    zeros.pop();   // flip the most‐recent kept zero
                    flips++;
                    ps += 2;       // flipping gives +2 to all suffix sums
                }
            }
        }

        // update max_ps = max over ps[0..i-2]
        if (i >= 1) {
            max_ps = max(max_ps, prev);
        }
    }

    cout << flips << "\n";
    return 0;
}
0