제출 #1149063

#제출 시각아이디문제언어결과실행 시간메모리
1149063_8_8_Chorus (JOI23_chorus)C++17
61 / 100
7094 ms2576 KiB
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

const int  N = (int)1e6 + 10, MOD = 998244353, inf = (int)1e9;

int n, k, a[N], b[N], px[N * 2], py[N * 2], f[N * 2];
string s;

ll dop = 0;
void make() {
    int bal = 0;
    string ret;
    for(int i = 0, col = 0; i < n + n; ++i) {
        if(s[i] == 'A') {
            ret += s[i];
            dop += col;
            bal++;
        } else {
            if(bal) {
                bal--;
                ret += s[i];
            } else {
                col++;
            }
        }
        while(col && bal) {
            ret += 'B';
            bal--;
            col--;
        }
    }
    s = ret;
}
ll dp[N], col[N];
pair<ll, int> solve(ll pen) {
    dp[0] = 0;
    col[0] = 0;
    for(int i = 1; i <= n; i++) {
        dp[i] = (ll)1e18;
    }
    for(int l = 0; l < n; l++) {
        ll sum = dp[l] + pen;
        for(int r = l + 1; r <= n; r++) {
            sum += max(0, f[a[r]] - l);
            if(sum < dp[r]) {
                dp[r] = sum;
                col[r] = col[l] + 1;
            }
        }
    }
    // for(int i = 1; i <= n; i++) {
    //     cout << i << ' ' << dp[i] << '\n';
    // }
    return {dp[n], col[n]};
}
void test() {
    cin >> n >> k;
    cin >> s;
    make();
    int fx = 1, fy = 1;
    for(int i = 1; i <= n + n; i++) {
        if(s[i - 1] == 'A') {
            a[fx++] = i;
        } else {
            b[fy++] = i;
            f[i]++;
        }
    }
    for(int i = 1; i <= n + n; i++) {
        f[i] += f[i - 1];
    }
    // auto [x, y] = solve(0);
    // cout << x << ' ' << y;
    // return;
    ll l = -1, r = (ll)1e14, res;
    while(r - l > 1) {
        ll mid = (l + r) >> 1;
        auto [val, t] = solve(mid);
        if(t <= k) {
            r = mid;
            res = val - k * 1ll * mid;
        } else {
            l = mid;
        }
    }
    cout << res + dop << '\n';
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    int t = 1;
    // cin >> t;

    while(t--) {
        test();
    }
}

#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...