Print Article

题目描述

Zero has an old printer that doesn’t work well sometimes. As it is antique, he still like to use it to print articles. But it is too old to work for a long time and it will certainly wear and tear, so Zero use a cost to evaluate this degree.
One day Zero want to print an article which has $N$ words, and each word $i$ has a cost $C_i$ to be printed. Also, Zero know that print $k$ words in one line will cost
$$\left(\sum_{i=1}^k C_i\right)^2+M$$
$M$ is a const number.
Now Zero want to know the minimum cost in order to arrange the article perfectly.

算法分析

$$f_i=\min(f_j+(s_i-s_j)^2+M)$$

$$f_j+(s_i-s_j)^2+M \le f_k+(s_i-s_k)^2+M$$

\begin{align} f_j-2s_is_j+s_j^2 &\le f_k-2s_is_k+s_k^2 \\ f_j+s_j^2-(f_k+s_k^2) &\le 2s_i(s_j-s_k) \\ {f_j+s_j^2-(f_k+s_k^2) \over 2s_j-2s_k} &\le s_i \end{align}

代码

#include <algorithm>
#include <cstdio>
#include <cstring>

static int const N = 500005;
int a[N], s[N], f[N], que[N];

int detx(int i, int j) { return s[j] - s[i] << 1; }

int dety(int i, int j) { return f[j] + s[j] * s[j] - f[i] - s[i] * s[i]; }

int main() {
for (int n, m; ~scanf("%d%d", &n, &m);) {
for (int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
for (int i = 1; i <= n; ++i)
s[i] = s[i - 1] + a[i];
int qb = 0, qe = 1;
for (int i = 1; i <= n; ++i) {
for (; qb + 1 < qe &&
dety(que[qb], que[qb + 1]) <= s[i] * detx(que[qb], que[qb + 1]);
++qb)
;
f[i] = f[que[qb]] + (s[i] - s[que[qb]]) * (s[i] - s[que[qb]]) + m;
for (; qb + 1 < qe &&
dety(que[qe - 2], que[qe - 1]) * detx(que[qe - 1], i) >=
dety(que[qe - 1], i) * detx(que[qe - 2], que[qe - 1]);
--qe)
;
que[qe++] = i;
}
printf("%d\n", f[n]);
}
return 0;
}


418 I'm a teapot