#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5;
int n, k, a[maxn + 1], pre[maxn + 1], trace[maxn + 1][201];
long long dp[maxn + 1][201], bestPos = 0;;
struct line{
long long a, b;
mutable long double p;
int id;
bool operator < (const line other)const{
if (other.a == 1e18 && other.b == 1e18) return p < other.p;
return a < other.a;
}
};
struct LINE_CONTAINER{
multiset<line> ms;
inline bool del(multiset<line>::iterator x, multiset<line>::iterator y){
if (y == ms.end()){
x->p = 1e18;
return false;
}
if (x->a == y->a){
x->p = (x->b >= y->b) ? 1e18 : -1e18;
}
else x->p = (long double)(y->b - x->b) / (long double)(x->a - y->a);
return x->p >= y->p;
}
inline void update(long long a, long long b, int i){
multiset<line>::iterator x = ms.insert({a, b, 0, i}), y = next(x);
while(del(x, y)) y = ms.erase(y);
if (x != ms.begin()){
y = prev(x);
if (del(y, x)) ms.erase(x);
}
else y = x;
while(y != ms.begin()){
x = prev(y);
if (del(x, y)){
del(x, ms.erase(y));
y = x;
}
else break;
}
}
inline pair<long long, int> get(long long x){
multiset<line>::iterator it = ms.lower_bound({(long long)1e18, (long long)1e18, (long double)x});
if (it == ms.end()) return {-1e18, 0};
return {it->a * x + it->b, it->id};
}
};
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for (int i = 1; i <= n; ++i){
cin >> a[i];
pre[i] = pre[i - 1] + a[i];
}
vector<LINE_CONTAINER> lc(k);
lc[0].update(0, 0, 0);
for (int i = 0; i <= n; ++i)
for (int j = 0; j <= k; ++j) {
dp[i][j] = -1e18;
trace[i][j] = 0;
}
dp[0][0] = 0;
for (int i = 1; i <= n; ++i){
for (int j = 1; j <= min(i, k); ++j){
pair<long long, int> g = lc[j - 1].get(pre[n] - pre[i]);
dp[i][j] = g.first + pre[i] * (pre[n] - pre[i]);
if (j < k && dp[i][j] > -1e18) lc[j].update(-(long long)pre[i], dp[i][j], i);
if (j == k && i < n && dp[i][k] > dp[bestPos][k]) bestPos = i;
trace[i][j] = g.second;
}
}
cout << dp[bestPos][k] << '\n';
int curPos = bestPos;
int curK = k;
vector<int> cuts;
while (curPos != 0 && curK > 0) {
cuts.push_back(curPos);
int prev = trace[curPos][curK];
curPos = prev;
--curK;
}
reverse(cuts.begin(), cuts.end());
for (int x : cuts) cout << x << ' ';
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... |