#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define X first
#define Y second
#define SZ(a) ((int)a.size())
#define ALL(v) v.begin(), v.end()
#define pb push_back
struct node {
int first, sz;
ll sum;
};
int lft[1000005];
list<node>::iterator arr[1000005];
int main() {
ios::sync_with_stdio(0), cin.tie(0);
int n, k;
long long ans = 0;
string s;
cin >> n >> k >> s;
if (n > 5000) return 0;
vector<int> plA, plB;
for (int i = 0; i < n + n; ++i) {
if (s[i] == 'B')
plB.pb(i);
else
plA.pb(i), lft[SZ(plA)] = SZ(plB);
}
const ll INF = 1e18;
vector<vector<ll>> dp(k + 1, vector<ll>(n + 1, INF));
ll fin = INF;
dp[0][0] = 0;
for (int i = 1; i <= k; ++i) {
for (int j = 1; j <= n; ++j) {
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1]);
int sz = 0;
ll sum = 0;
for (int p = j; p > 0; --p) {
++sz;
sum += lft[p];
dp[i][j] = min(dp[i][j], dp[i - 1][p - 1] + sum - sz * (p - 1));
}
}
fin = min(fin, dp[i][n]);
}
cout << ans + fin << "\n";
/*list<node> grp;
typedef pair<ll, int> pr;
priority_queue<pr, vector<pr>, greater<pr>> pq;
node cur;
cur.first = -1;
for (int i = 0; i < n; ++i) {
if (cur.first == -1 || plA[i] > plB[cur.first]) {
if (cur.first != -1)
grp.pb(cur);
cur.first = i;
cur.sz = 1;
cur.sum = lft[i];
}
else {
cur.sz += 1;
cur.sum += lft[i];
}
}
grp.pb(cur);
auto cal = [&](list<node>::iterator it) {
if (next(it) == grp.end()) return -1LL;
ll cst;
cst = next(it)->sum - it->first * next(it)->sz;
return cst;
};
auto rm = [&](list<node>::iterator it) {
it->sz += next(it)->sz;
it->sum += next(it)->sz * it->first;
arr[next(it)->first] = grp.end();
grp.erase(next(it));
if (next(it) != grp.end())
pq.push(pr(cal(it), it->first));
if (it != grp.begin())
pq.push(pr(cal(prev(it)), prev(it)->first));
};
for (int i = 0; i < n; ++i)
arr[i] = grp.end();
for (auto it = grp.begin(); next(it) != grp.end(); ++it) {
arr[it->first] = it;
pq.push(pr(cal(it), it->first));
}
cerr << s << "\n";
for (int i = 0; i < n; ++i)
cerr << plA[i] << " ";
cerr << endl;
for (int i = 0; i < n; ++i)
cerr << plB[i] << " ";
cerr << endl;
cerr << ans << "\n";
while (!pq.empty() && SZ(grp) > k) {
auto [cst, first] = pq.top();
pq.pop();
if (arr[first] == grp.end() || cst != cal(arr[first])) continue;
ans += cst;
rm(arr[first]);
}
assert(SZ(grp) <= k);
cout << ans << "\n";*/
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
8148 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
8148 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
8148 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
8148 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
8148 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |