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>
using namespace std;
#define sz(v) int(v.size())
#define ar array
typedef long long ll;
const int N = 5e3+10, MOD = 1e9+7;
int n, K, small[N];
int ps[N], l_use[N];
vector<int> one, two;
// min CHT with
// - slopes decreasing
// - query x increasing
struct Line {
int m, b;
int calc(int x) {
return m * x + b;
}
};
struct CHT {
deque<Line> lines;
void add(int m, int b) {
while (sz(lines) >= 2) {
auto A = lines.end()[-2];
auto B = lines.end()[-1];
if ((b - A.b) * (A.m - m) <= (B.b - A.b) * (A.m - B.m)) lines.pop_back();
else break;
}
lines.push_back({m, b});
}
int qry(int x) {
while (sz(lines) >= 2) {
auto A = lines[0];
auto B = lines[1];
// (B.b - A.b) / (A.m - B.m) <= x
if ((B.b - A.b) <= x * (A.m - B.m)) lines.pop_front();
else break;
}
return lines[0].calc(x);
}
};
void solve() {
cin >> n >> K;
for (int i = 0; i < 2 * n; i++) {
char c; cin >> c;
if (c == 'A') one.push_back(i);
else two.push_back(i);
}
for (int i = 0; i < n; i++) {
small[i] = lower_bound(two.begin(), two.end(), one[i]) - two.begin();
}
for (int i = 0; i < n; i++) {
ps[i] = small[i] + (i ? ps[i-1] : 0);
l_use[i] = -(i ? ps[i-1] : 0);
for (int j = i; j < n; j++) {
if (small[j] < i) {
l_use[i] -= small[j] - i;
}
}
}
vector<int> prv(n, MOD);
for (int k = 1; k <= K; k++) {
vector<int> nxt(n, MOD);
CHT lines;
for (int i = 0; i < n; i++) {
lines.add(-i, i * i - i + l_use[i] + (i == 0 ? 0 : prv[i-1]));
nxt[i] = lines.qry(i) + ps[i];
int l = small[i];
if (l <= i) {
nxt[i] = min(nxt[i], (l == 0 ? 0 : prv[l-1]));
}
}
swap(prv, nxt);
}
cout << prv[n-1] << '\n';
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int T = 1;
// cin >> T;
while (T--) 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... |