This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 5e3 + 42, INF = 1e12 + 42;
deque<int> imin, a, b;
vector<int> pre, upd[N];
int n, k, cumul[N], fi[N], dp[N][N];
int evalCHT(int x) {
if(a.empty()) return INF;
if((int)a.size() == 1)
return a[0] * x + b[0];
if(a[0] * x + b[0] > a[1] * x + b[1]) {
a.pop_front();
b.pop_front();
}
return a[0] * x + b[0];
}
void pushCHT(int A, int B) {
int sz = (int)a.size();
while(sz >= 2 && (B - b[sz-1]) * (a[sz-2] - a[sz-1]) <= (b[sz-1] - b[sz-2]) * (a[sz-1] - A)) {
sz--;
a.pop_back();
b.pop_back();
}
a.push_back(A);
b.push_back(B);
}
void add(int i, int nbG) {
if(fi[i] == i) {
pushCHT(-i, dp[nbG-1][i] + i * fi[i] - cumul[fi[i]]);
return;
}
upd[fi[i]].push_back(i);
while(!imin.empty() && dp[nbG-1][imin.back()] > dp[nbG-1][i])
imin.pop_back();
imin.push_back(i);
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int x = 0;
cin >> n >> k;
for(int i = 0; i < N; i++)
fi[i] = N-1;
for(int i = 0; i < 2*n; i++) {
char c; cin >> c;
if(c == 'A') {
if(fi[x] == N-1)
fi[x] = (int)pre.size();
pre.push_back(x);
} else {
x++;
}
}
for(int i = n-1; i > -1; i--)
if(fi[i] == N-1)
fi[i] = fi[i+1];
for(int i = 0; i <= n; i++)
fi[i] = max(fi[i], i);
for(int i = 1; i <= n; i++)
cumul[i] = cumul[i-1] + pre[i-1];
for(int i = 1; i <= n; i++)
dp[0][i] = INF;
for(int nbG = 1; nbG <= k; nbG++) {
a.clear();
b.clear();
imin.clear();
for(int i = 0; i < N; i++)
upd[i].clear();
add(0, nbG);
for(int i = 1; i <= n; i++) {
for(int j : upd[i]) {
pushCHT(-j, dp[nbG-1][j] + j * fi[j] - cumul[fi[j]]);
if(!imin.empty() && imin[0] == j)
imin.pop_front();
}
dp[nbG][i] = evalCHT(i) + cumul[i];
if(!imin.empty())
dp[nbG][i] = min(dp[nbG][i], dp[nbG-1][imin[0]]);
add(i, nbG);
}
}
cout << dp[k][n] << '\n';
}
# | 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... |