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 <iostream>
#include <deque>
#include <algorithm>
#include <cstring>
using namespace std;
// l[n] is bad if l[n - 1] intersects l[n + 1] before l[n] does
// => l[0] is bad if l[1] intersects l[-1] before l[0] does
using ll = long long;
const int N = 1e5;
const int K = 200;
int n, k, par[K + 5][N + 5];
ll a[N + 5], pfx_sum[N + 5], dp[N + 5];
deque<int> l;
ll ps(int i) {
return pfx_sum[i];
}
ll ss(int i) {
return pfx_sum[n] - pfx_sum[i - 1];
}
ll f(int li, ll x) {
return -ps(li) * x + dp[li];
}
bool firstIsBad(int l1, int l2, int l0) {
ll m1 = -ps(l1), c1 = dp[l1];
ll m2 = -ps(l2), c2 = dp[l2];
ll m0 = -ps(l0), c0 = dp[l0];
return (c2 - c0) * (m0 - m1) >= (c1 - c0) * (m0 - m2); // ((c2 - c0) / (m0 - m2)) > ((c1 - c0) / (m0 - m1))
}
void dfs(int i, int s) {
cout << i << ' ';
if (s > 1) dfs(par[s][i], s - 1);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> k;
a[0] = pfx_sum[0] = 0;
for (int i = 1; i <= n; i++) {
cin >> a[i];
pfx_sum[i] = a[i] + pfx_sum[i - 1];
}
memset(par, -1, sizeof par);
for (int s = 1; s <= k; s++) {
deque<int> l_new;
for (int i = n; i >= 1; i--) {
dp[i] = -1;
while (l.size() > 1 and (i <= l[0] or f(l[0], ss(i + 1)) <= f(l[1], ss(i + 1)))) l.pop_front();
if (s == 1) dp[i] = ps(i) * ss(i + 1);
else if (not l.empty() and l[0] < i) {
dp[i] = ps(i) * ss(i + 1) + f(l[0], ss(i + 1));
par[s][i] = l[0];
}
if (dp[i] == -1) continue;
while (l_new.size() > 1 and firstIsBad(l_new[0], l_new[1], i)) l_new.pop_front();
l_new.push_front(i);
}
reverse(l_new.begin(), l_new.end());
l = l_new;
}
ll ans = 1;
for (int i = 1; i <= n; i++) {
if (dp[ans] < dp[i]) ans = i;
}
cout << dp[ans] << '\n';
dfs(ans, k);
cout << '\n';
return 0;
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |