#include <bits/stdc++.h>
using namespace std;
#define int long long
#define inf (long long)(1e15)
signed main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
//start here
int N,k;cin >> N >> k;
vector<vector<int>> dp(k+1,vector<int>(N+1,inf));
string s;cin >> s;
{// init k;
int Acnt = 0;
int Bcnt = 0;
int curSwap = 0;
dp[1][0] = 0;
for(auto i:s){
if(i == 'A'){
curSwap += Bcnt;
Acnt++;
dp[1][Acnt] = curSwap;
}else{
Bcnt++;
}
}
}
for(int l = 1;l <= k-1;l++){
// push to next layer;
for(int i = 0;i <= N;i++){
// chose d additional;
string ns;
{// create ns
int Acnt = 0;
int Bcnt = 0;
for(auto c:s){
if(c == 'A'){
if(Acnt >= i) ns.push_back('A');
Acnt++;
}else{
if(Bcnt >= i) ns.push_back('B');
Bcnt++;
}
}
}
{// push
int Acnt = 0;
int Bcnt = 0;
int curSwap = 0;
dp[l+1][i] = min(dp[l+1][i],dp[l][i]);
// cout << l << " " << i << ":" << ns << endl;
for(auto c:ns){
if(c == 'A'){
curSwap += Bcnt;
Acnt++;
dp[l+1][i+Acnt] = min(dp[l+1][i+Acnt],curSwap+dp[l][i]);
}else{
Bcnt++;
}
}
}
}
}
int ans = inf;
for(int l = 1;l <= k;l++){
ans = min(ans,dp[l][N]);
}
// //! debug;
// for(int l = 1;l <= k;l++){
// for(int i = 1;i <= N;i++){
// cout << dp[l][i] << " ";
// }
// cout << endl;
// }
// cout << endl;
// //! debug end
cout << ans;
}
// AAAABBBBAB
# | 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... |