状态转移方程很容易想到:
dp[i] = dp[j] + (sum[i] - sum[j] )^2 + M;( 0 <= j < i )
变形得
dp[i] = -2sum[i] * sum[j] + dp[j] + sum[j] ^2 + sum[i] ^2 + M;
令 a = 2sum[i] , x = sum[j] , y = dp[j] + sum[j] ^2
实际上要求使 G = -a * x + y 最小的点
变形 y = a * x + G
意思就是求使G最大的点
这时我们可以维护一个下凸点的栈,因为如果决策中存在上凸点,该点一定不是最优的
然后每次从这个栈中找决策点,又因为这个栈是下凸的,所以决策时单调的
AC代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
int N, M;
long long sum[550000];
long long dp[550000];
int pos[550000], s, e;
double calc( int j, int i ){
return dp[j] + sum[j] * sum[j] - 2 * sum[i] * sum[j];
}
int main(){
while( scanf( "%d%d", &N, &M ) != EOF ){
sum[0] = 0;
dp[0] = 0;
for( int i = 1; i <= N; i++ ){
scanf( "%lld", &sum[i] );
sum[i] += sum[i-1];
}
s = 0; e = -1;
pos[++e] = 0;
for( int i = 1; i <= N; i++ ){
while( s < e && calc( pos[s], i ) >= calc( pos[s+1], i ) ) s++;
dp[i] = calc( pos[s], i ) + sum[i] * sum[i] + M;
while( s < e ){
//这里不要直接用double来算斜率,因为精度不够,转换成积
long long k1 = ( dp[i] + sum[i] * sum[i] - dp[pos[e]] - sum[pos[e]] * sum[pos[e]] ) * ( sum[pos[e]] - sum[pos[e-1]] );
long long k2 = ( dp[pos[e]] + sum[pos[e]] * sum[pos[e]] - dp[pos[e-1]] - sum[pos[e-1]] * sum[pos[e-1]] ) * ( sum[i] - sum[pos[e]] );
if( k2 >= k1 ){
e--;
}else{
break;
}
}
pos[++e] = i;
}
printf( "%lld\n", dp[N] );
}
return 0;
}