# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
762535 | Ahmed57 | Split the sequence (APIO14_sequence) | C++17 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll is_query = -(1LL<<62);
struct Line {
ll m,b,idx;
mutable function<const Line*()> succ;
bool operator<(const Line& rhs) const {
if (rhs.b != is_query) return m < rhs.m;
const Line* s = succ();
if (!s) return 0;
ll x = rhs.m;
return b - s->b < (s->m - m) * x;
}
};
struct HullDynamic : public multiset<Line> { // will maintain upper hull for maximum
bool bad(iterator y) {
auto z = next(y);
if (y == begin()) {
if (z == end()) return 0;
return y->m == z->m && y->b <= z->b;
}
auto x = prev(y);
if (z == end()) return y->m == x->m && y->b <= x->b;
return (x->b - y->b)*(z->m - y->m) >= (y->b - z->b)*(y->m - x->m);
}
void insert_line(ll m, ll b,int idx) {
auto y = insert({ m, b,idx });
y->succ = [=] { return next(y) == end() ? 0 : &*next(y); };
if (bad(y)) { erase(y); return; }
while (next(y) != end() && bad(next(y))) erase(next(y));
while (y != begin() && bad(prev(y))) erase(prev(y));
}
pair<ll,ll> eval(ll x) {
auto l = *lower_bound((Line) { x, is_query });
return {l.m * x + l.b , l.idx};
}
};
long long dp[100001][204];
int lol[100001][204];
signed main(){
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
long long n,k;
cin>>n>>k;
long long arr[n+1] = {0};
for(int i = 1;i<=n;i++){
cin>>arr[i];
arr[i]+=arr[i-1];
}
if(n==1){
cout<<0<<endl;
return 0;
}
for(int j = 1;j<=k+1;j++){
HullDynamic cht;
cht.insert_line(arr[j-1],(dp[j-1][j-1]-arr[j-1]*arr[n]),j-1);
for(int i = j;i<=n;i++){
dp[i][j] = arr[i]*arr[n]-arr[i]*arr[i]+cht.eval(arr[i]).first;
lol[i][j] = cht.eval(arr[i]).second;
cht.insert_line(arr[i],(dp[i][j-1]-arr[i]*arr[n]),i);
}
}
k++;
cout<<dp[n][k]<<endl;
int x = n;
vector<ll> ha;
while(k>1){
ha.push_back(max(1LL,lol[x][k]));
x = lol[x][k];k--;
}
for(int i = ha.size()-1;i>=0;i--){
cout<<ha[i]<<" ";
}
}