1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <cstdio> #include <algorithm> using namespace std; typedef long long LL; const LL inf = 1e18; const int N = 1e5 + 10, M = 210; LL s[N], f[N][M]; int hd, tl, q[N]; int n, m, pre[N][M]; double slp(int x, int a, int b) { if (s[a] == s[b]) return inf; return (double)(f[a][x] - s[a] * s[a] - f[b][x] + s[b] * s[b]) / (double)(s[a] - s[b]); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) { scanf("%lld", &s[i]); s[i] += s[i - 1]; } for (int j = 1; j <= m; j++) { hd = 1, tl = 0; for (int i = j; i <= n; i++) { while (hd < tl && slp(j - 1, q[hd], q[hd + 1]) > -s[i]) hd++; pre[i][j] = q[hd]; f[i][j] = f[q[hd]][j - 1] + s[q[hd]] * (s[i] - s[q[hd]]); while (hd < tl && slp(j - 1, q[tl], q[tl - 1]) < slp(j - 1, q[tl], i)) tl--; q[++tl] = i; } } printf("%lld\n", f[n][m]); for (int i = pre[n][m]; m; i = pre[i][--m]) printf("%d ", i); return 0; }
|
Gitalk 加载中 ...