Description
Solution
又是一道斜率优化题,有了上一道题的经验,这一道题就很顺利的做完了
关键点:
(f_i = f_j + a(s_i-s_j)^2+b(si-sj)+c)
(j)比(k)优:(displaystylefrac{f_j-f_k+as_j^2-bs_j-as_k^2+bs_k}{2a(s_j-s_k)}<s_i)
(F_x = as_x^2 - bs_x + f_x,G_x = 2as_x)
Code
#include <cstdio>
#include <cmath>
#include <algorithm>
const double eps = 1e-10;
const int N = 1e6+10;
typedef long long LL;
LL a, b, c, n;
LL s[N], t[N], F[N], G[N], f[N];
LL q[N], qhd, qtl;
int dcmp(double x) {
if (fabs(x) < eps) return 0;
else if (x > 0) return 1;
else return -1;
}
double K(int x, int y) {
return 1.0 * (F[x] - F[y]) / (G[x] - G[y]);
}
bool check(int x, int y, int z) {
if (dcmp(K(x, y) - K(y, z)) == 1) return true;
else return false;
}
void dp() {
q[qtl++] = 0;
for (int i = 1; i <= n; ++i) {
while (qhd < qtl-1 && dcmp(K(q[qhd], q[qhd+1]) - s[i]) == -1) qhd++;
int j = q[qhd];
f[i] = f[j] + a * (s[i] - s[j]) * (s[i] - s[j]) + b * (s[i] - s[j]) +c;
F[i] = f[i] + t[i];
while (qhd < qtl-1 && check(q[qtl-2], q[qtl-1], i)) qtl--;
q[qtl++] = i;
}
}
int main () {
scanf("%lld%lld%lld%lld", &n, &a, &b, &c);
LL x;
for (int i = 1; i <= n; ++i) {
scanf("%lld", &x);
s[i] = s[i-1] + x;
t[i] = a * s[i] * s[i] - b * s[i];
G[i] = 2 * a * s[i];
}
dp();
printf("%lld
", f[n]);
return 0;
}