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;
#define int long long
using ll = long long;
const int N = 1e5 + 10;
const int K = 200 + 10;
int n, k, a[N], dp[N][K], b[N][K];
struct Line {
int id;
mutable ll k, m, p;
bool operator<(const Line& o) const { return k < o.k; }
bool operator<(ll x) const { return p < x; }
};
struct LineContainer : multiset<Line, less<>> {
// (for doubles, use inf = 1/.0, div(a,b) = a/b)
static const ll inf = LLONG_MAX;
ll div(ll a, ll b) { // floored division
return a / b - ((a ^ b) < 0 && a % b); }
bool isect(iterator x, iterator y) {
if (y == end()) return x->p = inf, 0;
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 id) {
auto z = insert({id, k, m, 0}), 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) {
if(size() == 0) return {0ll, 0};
auto l = *lower_bound(x);
return {l.k * x + l.m, l.id};
}
};
signed main(){
iostream::sync_with_stdio(false);cin.tie(nullptr);
cin >> n >> k;
for(int i = 1;i<=n;i++)cin >> a[i];
for(int i = 1;i<=n;i++)a[i] += a[i - 1];
vector<LineContainer> lc(k + 1);
for(int i = 1;i<=n;i++){
for(int l = 1;l<min(i, k + 1);l++){
auto [val, id] = lc[l - 1].query(a[i]);
dp[i][l] = val; b[i][l] = id;
}
for(int l = 0;l<min(i, k + 1);l++){
lc[l].add(a[i], -a[i]*a[i] + dp[i][l], i);
}
}
cout << dp[n][k] << "\n";
vector<int> v = {n};
for(int l = k;l>=1;l--){
v.push_back(b[v.back()][l]);
}
reverse(v.begin(), v.end());v.pop_back();reverse(v.begin(), v.end());
for(int e : v)cout << e << " ";
cout << "\n";
}
Compilation message (stderr)
sequence.cpp: In function 'int main()':
sequence.cpp:46:18: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
46 | auto [val, id] = lc[l - 1].query(a[i]);
| ^
# | 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... |