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 FAST_IO ios_base::sync_with_stdio(0); cin.tie(nullptr)
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define REP(n) FOR(O, 1, (n))
#define f first
#define s second
#define pb push_back
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long double ld;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int MAXN = 100100;
const ll INF = 1e16;
struct line {
ll k, b;
int id;
line (ll _k, ll _b, int _id) : k (_k), b (_b), id (_id) {}
ll operator() (ll x) {
return k * x + b;
}
};
ld intersection (line p, line q) {
ld dy = ((ld)(q.b - p.b));
ld dx = ((ld)(p.k - q.k));
return dy / dx;
}
ll dp[210][MAXN];
int pr[210][MAXN];
int n, k;
ll a[MAXN], pref[MAXN];
deque<line> dq[210];
void ins (int g, int id) {
ll k = pref[id];
ll b = dp[g][id] - pref[id] * pref[id];
line newL (k, b, id);
while (dq[g].size() > 0 && dq[g][dq[g].size()-1].k == newL.k) {
dq[g].pop_back();
}
while (dq[g].size() > 1 &&
intersection(dq[g][dq[g].size()-2], newL) < intersection(dq[g][dq[g].size()-2], dq[g][dq[g].size()-1])) {
dq[g].pop_back();
}
dq[g].push_back(newL);
}
int getMaxId (int g, ll x) {
int sz = dq[g].size();
if (sz == 1) return dq[g][0].id;
if (x >= intersection(dq[g][sz-2], dq[g][sz-1]))
return dq[g][sz-1].id;
int le = 0, ri = sz-2;
while (le < ri) {
int m = (le+ri)/2;
ld inter = intersection(dq[g][m], dq[g][m+1]);
if (x > inter) le = m+1;
else ri = m;
}
return dq[g][le].id;
}
int main()
{
FAST_IO;
cin >> n >> k;
FOR(i, 1, n) cin >> a[i];
FOR(i, 1, n) pref[i] = pref[i-1] + a[i];
dp[0][0] = 0;
//FOR(i, 1, n) dp[0][i] = -INF;
ins(0, 0);
FOR(g, 1, k+1) FOR(i, g, n) {
dp[g][i] = -INF;
//if (i < g) continue;
/* FOR(j, g-1, i-1) {
ll k = pref[j];
ll b = dp[g-1][j] - pref[j] * pref[j];
ll x = pref[i];
ll cr = k*x + b;
if (cr > dp[g][i]) {
dp[g][i] = k * x + b;
pr[g][i] = j;
}
} */
ll x = pref[i];
int j = getMaxId(g-1, x);
ll k = pref[j];
ll b = dp[g-1][j] - pref[j] * pref[j];
pr[g][i] = j;
dp[g][i] = k * x + b;
ins(g, i);
}
cout << dp[k+1][n] << "\n";
int g = k+1, i = n;
while (g > 0) {
i = pr[g][i];
g--;
if (g > 0) cout << i << " ";
}
cout << "\n";
return 0;
}
/*
7 3
4 1 3 4 0 2 3
*/
# | 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... |