This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("Ofast","unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int INF = 1e18;
struct fenwick{
vector<int> tree;
int n;
fenwick(int n):n(n),tree(n+1){}
void add(int k,int x){
while(k<=n){
tree[k]+=x;
k+=k&-k;
}
}
void reset(){
fill(tree.begin(),tree.end(),0ll);
}
int get(int k){
int ans = 0;
while(k){
ans+=tree[k];
k-=k&-k;
}
return ans;
}
};
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n,k;
cin >> n >> k;
string s;
cin >> s;
s.insert(s.begin(),'$');
vector<int> posA(n+1);
vector<int> posB(n+1);
int cntA = 0,cntB = 0;
for(int i=1;i<=2*n;i++){
if(s[i]=='A'){
posA[++cntA]=i;
} else {
posB[++cntB]=i;
}
}
fenwick addedA(2*n);
fenwick addedB(2*n);
auto solve = [&](int penalty){
vector<pair<int,int>> DP1(n+1,{INF,-INF});
vector<pair<int,int>> DP2(n+1,{INF,-INF});
DP1[0]={0,0};
DP2[0]={0,0};
for(int i=1;i<=n;i++){
int ans = penalty;
addedA.reset();
addedB.reset();
for(int j=i+1;j<=n;j++)addedB.add(posB[j],1);
for(int j=i;j;j--){
ans+=i-j-addedA.get(posB[j]);
addedB.add(posB[j],1);
ans+=addedB.get(posA[j]);
addedA.add(posA[j],1);
DP1[i]=min(DP1[i],{DP1[j-1].first+ans,DP1[j-1].second-1});
DP2[i]=min(DP2[i],{DP2[j-1].first+ans,DP2[j-1].second+1});
}
}
DP1[n].second*=-1ll;
auto mini = DP2[n];
auto maxi = DP1[n];
if(mini.second>k)return mini;
if(maxi.second<=k)return maxi;
return make_pair(mini.first,k);
};
int best_penalty = -1;
for(int jump=(1ll<<40);jump;jump/=2ll){
if(solve(best_penalty+jump).second>k)best_penalty+=jump;
}
// for(int i=0;i<=10;i++)cout<<solve(i).second<<'\n';
best_penalty++;
cout << solve(best_penalty).first-solve(best_penalty).second*best_penalty << '\n';
}
Compilation message (stderr)
chorus.cpp: In constructor 'fenwick::fenwick(long long int)':
chorus.cpp:11:6: warning: 'fenwick::n' will be initialized after [-Wreorder]
11 | int n;
| ^
chorus.cpp:10:14: warning: 'std::vector<long long int> fenwick::tree' [-Wreorder]
10 | vector<int> tree;
| ^~~~
chorus.cpp:12:2: warning: when initialized here [-Wreorder]
12 | fenwick(int n):n(n),tree(n+1){}
| ^~~~~~~
# | 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... |