Print Article
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
Also, Zero know that print
k
words in one line will cost
Now Zero want to know the minimum cost in order to arrange the article perfectly.
Input
There are many test cases.
For each test case, There are two numbers
N
and
Then, there are
N
numbers in the next
Output
A single number, meaning the mininum cost to print the article.
Sample Input
5 5
5
9
5
7
5
Sample Output
230
Solution
设
fi
表示前
i
个字母打出来的最少费用。
推出斜率公式,
其中,
Code
#include <iostream>
#include <cstdio>
#define LL long long
#define Min(x,y) ((x)<(y)?(x):(y))
using namespace std;
LL n,m,Max_Right,lastcost;
LL c[500010],A[500010],f[500010],As[500010];
double ks[500010];
int main(){
while(scanf("%lld%lld",&n,&m)!=EOF){
A[0]=0;
for(LL i=1;i<=n;i++){
scanf("%lld",&c[i]);
A[i]=A[i-1]+c[i];
}
lastcost=Max_Right=As[0]=f[0]=0;
ks[Max_Right+1]=9223372036854775807LL;ks[Max_Right]=-9223372036854775807LL;
for(LL i=1;i<=n;i++){
for(LL j=lastcost;j<=Max_Right;j++)
if(ks[j]<=A[i]&&ks[j+1]>=A[i]){
lastcost=j;
f[i]=f[j]+(A[i]-As[j])*(A[i]-As[j])+m;
for(LL k=Max_Right;k>=0;k--)
if((double)(f[i]+A[i]*A[i]-f[k]-As[k]*As[k])/(2*A[i]-2*As[k])>=ks[k]){
Max_Right=k+1;As[Max_Right]=A[i];f[Max_Right]=f[i];
ks[Max_Right]=(double)(f[i]+A[i]*A[i]-f[k]-As[k]*As[k])/(2*A[i]-2*As[k]);
ks[Max_Right+1]=9223372036854775807LL;
lastcost=Min(lastcost,Max_Right);
break;
}
break;
}
}
printf("%lld\n",f[n]);
}
return 0;
}