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;
typedef long long ll;
typedef long double ld;
struct line {
ll k, b;
line (ll k, ll b) : k(k), b(b) {}
};
ll f(const line &l, ll x) {
return l.k * x + l.b;
}
ld inter(const line &a, const line &b) {
return (ld)(a.b - b.b) / (b.k - a.k);
}
vector <line> s;
vector <int> idx;
void push(const line &l, int id) {
while ((int)s.size() && s[(int)s.size() - 1].k == l.k && s[(int)s.size() - 1].b <= l.b) {
s.pop_back();
idx.pop_back();
}
if (!s.empty() && s.back().k == l.k && s.back().b > l.b) return;
while ((int)s.size() >= 2) {
line a = s[(int)s.size() - 1];
line b = s[(int)s.size() - 2];
if (inter(l, a) < inter(l, b)) {
s.pop_back();
idx.pop_back();
}
else {
break;
}
}
s.push_back(l);
idx.push_back(id);
}
pair <ll, int> get(ll x) {
int l = -1, r = (int)s.size() - 1;
while (r - l > 1) {
int m = (l + r) >> 1;
if (f(s[m], x) < f(s[m + 1], x)) {
l = m;
}
else r = m;
}
return {f(s[r], x), idx[r]};
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.setf(ios::fixed); cout.precision(20);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
vector <int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
vector <vector <ll>> dp(n + 1, vector <ll> (k + 1));
vector <ll> pref(n + 1);
for (int i = 0; i < n; ++i) {
pref[i + 1] = pref[i] + a[i];
}
vector <vector <int>> who(n + 1, vector <int> (k + 1, -1));
//(pref[i] - pref[t]) * (pref[n] - pref[i]) + dp[t][j]
// pref[i] * (pref[n] - pref[i]) - pref[t] * pref[n] + pref[t] * pref[i] + dp[t][j]
for (int j = 1; j <= k; ++j) {
s.clear();
for (int i = 1; i <= n; ++i) {
push(line(pref[i - 1], -pref[i - 1] * pref[n] + dp[i - 1][j - 1]), i - 1);
auto p = get(pref[i]);
dp[i][j] = p.first + pref[i] * (pref[n] - pref[i]);
who[i][j] = p.second;
}
}
ll ans = -1;
int id = -1;
for (int i = 1; i <= n; ++i) {
if (dp[i][k] > ans) {
ans = dp[i][k];
id = i;
}
}
vector <int> where;
for (int cr = k; cr >= 1; --cr) {
where.push_back(id);
id = who[id][cr];
}
reverse(where.begin(), where.end());
cout << ans << '\n';
for (auto x : where) {
cout << x << ' ';
}
}
# | 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... |