# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1269459 | rayan_bd | 수열 (APIO14_sequence) | C++20 | 0 ms | 0 KiB |
#include <bits/stdc++.h>
using namespace std;
const int mxN = 1e5 + 2;
const int mxK = 202;
#define ll long long
pair<ll, int> dp[mxN];
ll pref[mxN];
struct Line {
mutable ll k, m, p, idx;
bool operator<(const Line& o) const { return k < o.k; }
bool operator<(int x) const { return p < x; }
};
struct LineContainer : multiset<Line, less<>> {
static const ll inf = LLONG_MAX;
ll div(ll a, ll b) { return a / b - ((a ^ b) < 0 && a % b); }
bool isect(iterator x, iterator y) {
if (y == end()) { x->p = inf; return false; }
if (x->k == y->k) x->p = x->m > y->m ? inf : -inf;
else x->p = div(y->m - x->m, x->k - y->k);
return x->p >= y->p;
}
void add(ll k, ll m, int idx) {
auto z = insert({k, m, 0, idx}), y = z++, x = y;
while (isect(y, z)) z = erase(z);
if (x != begin() && isect(--x, y)) isect(x, y = erase(y));
while ((y = x) != begin() && (--x)->p >= y->p)
isect(x, erase(y));
}
pair<ll, int> query(ll x) {
assert(!empty());
auto l = *lower_bound(x);
return {l.k * x + l.m, l.idx};
}
} cht;
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(nullptr);
int n, K;
cin >> n >> K;
for(int i = 1; i <= n; ++i){
cin >> pref[i];
pref[i] += pref[i - 1];
}
for(int i = 0; i <= n + 1; ++i){
for(int j = 0; j <= K; ++j){
dp[i][j] = {inf, 0};
}
}
for (int i = 1; i <= n + 1; i++) dp[i][0] = {0, i};
for (int k = 1; k <= K; k++) {
cht.clear();
for (int j = n; j >= 1; j--) {
cht.add(pref[j], (long long) dp[j+1][k - 1].first - pref[j] * pref[j], j);
auto [val, idx] = cht.query((long long) pref[n] + pref[j-1]);
dp[j][k] = {(long long) -pref[j-1] * pref[n] + val, idx};
}
}
cout << dp[1][K].first << "\n";
int i = 1;
while (K > 0 && i <= n) {
int j = dp[i][K].second;
if (j == -1) break;
cout << j << " ";
i = j + 1;
K--;
}
cout << "\n";
return 0;
}