Problem Description
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 Ci to be printed. Also, Zero know that print k words in one line will cost
M is a const number.
Now Zero want to know the minimum cost in order to arrange the article perfectly.
#include<stdio.h>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=500001;
int sum[maxn],a[maxn],dp[maxn],h,t,q[maxn],n,m;
/*dp[j]+M+(sum[i]-sum[j])^2<dp[k]+M+(sum[i]-sum[k])^2*/
/*(dp[j]+sum[j]^2-(dp[k]+sum[k]^2))/(2*(sum[j]-sum[k]))<sum[i]*/
inline const int read(){
register int f=1,x=0;
register char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
return x*f;
}
int up(int j,int k){
return dp[j]+sum[j]*sum[j]-(dp[k]+sum[k]*sum[k]);
}
int down(int j,int k){
return 2*(sum[j]-sum[k]);
}
void init(){
h=1,t=0;
}
int main(){
while(~scanf("%d%d",&n,&m)){
init();
for(register int i=1;i<=n;i++) {a[i]=read();sum[i]=sum[i-1]+a[i];}
q[++t]=0;//初始决策为0,不能抛弃
for(register int i=1;i<=n;i++){
while(h<t&&up(q[h+1],q[h])<=sum[i]*down(q[h+1],q[h])) h++;
dp[i]=dp[q[h]]+(sum[i]-sum[q[h]])*(sum[i]-sum[q[h]])+m;
while(h<t&&up(i,q[t])*down(q[t],q[t-1])<=up(q[t],q[t-1])*down(i,q[t])) t--;
q[++t]=i;
}
printf("%d\n",dp[n]);
}
}