/* 终于做斜率优化做得有些感觉了~ 和HDOJ3480很相似~我的这两份代码除了公式处理部分不同,其它部分都差不多~ (1)dp方程:dp[c][i]=min{dp[c-1][j]+w(j+1,i)},其中w(i,j)为段j+1~i的Strategic Value; (2)斜率不等式: 起初我用二位统计数组计算w(i,j),弄了很久i和j根本无法分离,只好另辟它径; 记s[i]=a[1]+a[2]+...+a[i]; sq[i]=a[1]^2+a[2]^2+...+a[i]^2; 有w(j,i)=[(s[i]-s[j-1])^2-(sq[i]-sq[j-1])]/2; 然后解dp[k][*]+w(k+1,i)<=dp[j][*]+w(j+1,i)得斜率不等式: 记y(j)=dp[j]+(s[j]^2+sq[j])/2; x(j)=s[j]; 有(y(k)-y(j))/(x(k)-x(j))<=s[i]; 然后就是直接套着写了~ */ #include <cstdio> #include <cstring> #include <iostream> using namespace std; typedef __int64 LL; const int NN=1005; int n,m,flag,r,f,a[NN],q[NN]; LL s[NN],sq[NN],dp[2][NN]; inline LL x(int j)//中间算错过一次,写成了s[j-1],囧... { return s[j]; } inline LL y(int j)//中间算错过一次,写成了s[j-1],囧... { return dp[flag^1][j]+(s[j]*s[j]+sq[j])/2; } inline LL w(int j,int i) { return ((s[i]-s[j-1])*(s[i]-s[j-1])+sq[j-1]-sq[i])/2; } inline LL g(int j,int i) { return dp[flag^1][j]+w(j+1,i); } inline int mult(int p1,int p2,int p0) { return (x(p1)-x(p0))*(y(p2)-y(p0))-(x(p2)-x(p0))*(y(p1)-y(p0)); } int main() { while (scanf("%d%d",&n,&m),n|m) { m++; for (int i=1; i<=n; i++) scanf("%d",&a[i]); if (m==n) { printf("0\n"); continue; } s[0]=0; sq[0]=0; for (int i=1; i<=n; i++) { s[i]=s[i-1]+a[i]; sq[i]=sq[i-1]+a[i]*a[i]; } //dp for (int i=1; i<=n; i++) dp[1][i]=w(1,i); for (int j=2; j<=m; j++) { flag=j%2; f=0,r=0; q[r++]=j-1; for (int i=j; i<=n; i++) { while (f<r-1 && g(q[f],i)>=g(q[f+1],i)) f++; dp[flag][i]=g(q[f],i); while (f<r-1 && mult(q[r-2], q[r-1],i)<=0) r--; q[r++]=i; } } printf("%I64d\n",dp[flag][n]); } return 0; }