#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 1e9;
int n, k, dp[5002][5002], t[5002], P[5002];
vector <int> ii[2];
string s;
int choose (int x) {
return x * (x - 1) / 2;
}
void recurse (int l1, int r1, int l2, int r2, int j) {
if (l1 > r1) {
return;
}
int i = (l1 + r1) / 2;
dp[i][j] = inf;
int opt = -1;
for (int p = min(r2, t[i]); p >= l2; p--) {
if (dp[i][j] > dp[p - 1][j - 1] + ii[0][i] * (t[i] - p) - choose(t[i] - p) - (P[t[i] - 1] - P[p - 1])) {
dp[i][j] = dp[p - 1][j - 1] + ii[0][i] * (t[i] - p) - choose(t[i] - p) - (P[t[i] - 1] - P[p - 1]);
opt = p;
}
}
recurse(l1, i - 1, l2, opt, j);
recurse(i + 1, r1, opt, r2, j);
}
void solve () {
cin >> n >> k >> s;
int bad = 0;
int cur = 0;
for (int i = 0; i < 2 * n; i++) {
if (s[i] == 'B') {
cur--;
} else {
cur++;
}
if (cur < 0) {
int j = i;
while (s[j] != 'A') {
j++;
}
bad += j - i;
swap(s[i], s[j]);
i--; cur++;
}
}
ii[0].push_back(0);
ii[1].push_back(0);
for (int i = 0; i < 2 * n; i++) {
ii[s[i] - 'A'].push_back(i + 1);
}
for (int i = 1; i <= n; i++) {
P[i] = P[i - 1] + ii[1][i];
}
for (int i = 1; i <= n; i++) {
dp[i][0] = inf;
}
for (int j = 1; j <= k; j++) {
int l = 1;
for (int i = 1; i <= n; i++) {
dp[i][j] = inf;
while (ii[1][l] < ii[0][i]) {
l++;
}
t[i] = l;
}
recurse(1, n, 1, n, j);
}
cout << bad + dp[n][k] << '\n';
}
signed main () {
ios::sync_with_stdio(0); cin.tie(0);
int tc = 1; //cin >> tc;
while (tc--) solve();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |