【题目链接】
【前置技能】
- 斜率优化DP
【题解】
- 设计状态 f [ i ] f[i] f[i]表示已经将 1 1 1 ~ i i i号士兵编好队的最大战斗力。答案就是 f [ n ] f[n] f[n]。
- 令 s u m [ i ] sum[i] sum[i]表示 1 1 1 ~ i i i号士兵的战斗力之和,那么由题意可得,转移方程 f [ i ] = m a x { f [ j ] + a ∗ ( s u m [ i ] − s u m [ j ] ) 2 + b ∗ ( s u m [ i ] − s u m [ j ] ) + c } f[i] = max\{f[j] + a * (sum[i] - sum[j]) ^ 2 + b * (sum[i] - sum[j]) + c\} f[i]=max{f[j]+a∗(sum[i]−sum[j])2+b∗(sum[i]−sum[j])+c},化简可得 f [ i ] = m a x { f [ j ] + a ∗ s u m [ j ] 2 − b ∗ s u m [ j ] − 2 ∗ a ∗ s u m [ i ] ∗ s u m [ j ] } + a ∗ s u m [ i ] 2 + b ∗ s u m [ i ] + c f[i] = max\{ f[j] + a * sum[j]^2 - b * sum[j] - 2 *a * sum[i] * sum[j] \} + a * sum[i]^2 + b * sum[i] + c f[i]=max{f[j]+a∗sum[j]2−b∗sum[j]−2∗a∗sum[i]∗sum[j]}+a∗sum[i]2+b∗sum[i]+c
- 以 ( s u m [ i ] , f [ i ] + a ∗ s u m [ i ] 2 − b ∗ s u m [ i ] ) (sum[i], f[i] + a * sum[i] ^2 - b*sum[i]) (sum[i],f[i]+a∗sum[i]2−b∗sum[i])为坐标,维护上凸壳,用 2 ∗ a ∗ s u m [ i ] 2*a*sum[i] 2∗a∗sum[i]切凸壳进行转移即可。
- 时间复杂度 O ( N ) O(N) O(N)
【代码】
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define LL long long
#define MAXN 1000010
using namespace std;
int n;
LL f[MAXN], sum[MAXN], a, b, c, l, r;
struct dot{LL x, y; int id;}q[MAXN];
dot operator - (dot a, dot b){
a.x -= b.x, a.y -= b.y;
return a;
}
LL operator * (dot a, dot b){
return a.x * b.y - a.y * b.x;
}
template <typename T> void chkmin(T &x, T y){x = min(x, y);}
template <typename T> void chkmax(T &x, T y){x = max(x, y);}
template <typename T> void read(T &x){
x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();}
x *= f;
}
int main(){
read(n);
read(a), read(b), read(c);
for (int i = 1; i <= n; ++i)
read(sum[i]);
for (int i = 1; i <= n; ++i)
sum[i] += sum[i - 1];
f[0] = 0;
q[l = r = 0] = (dot){0, 0, 0};
for (int i = 1; i <= n; ++i){
while (l < r && 2ll * a * sum[i] * (q[l + 1].x - q[l].x) <= q[l + 1].y - q[l].y) ++l;
int cur = q[l].id;
f[i] = f[cur] + a * (sum[i] - sum[cur]) * (sum[i] - sum[cur]) + b * (sum[i] - sum[cur]) + c;
dot tmp = (dot){sum[i], f[i] + a * sum[i] * sum[i] - b * sum[i], i};
while (l < r && (tmp - q[r]) * (q[r] - q[r - 1]) <= 0) --r;
q[++r] = tmp;
}
printf("%lld\n", f[n]);
return 0;
}