# [Hdu3507] 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 i has a cost Ci to be printed. Also, Zero know that print k words in one line will cost $(_{i=1}{k}C_{i}){2}+M$. M is a const number.

Now Zero want to know the minimum cost in order to arrange the article perfectly.

## 输入格式 InputFormat

There are many test cases. For each test case, There are two numbers N and M in the first line (0 ≤ n ≤ 500000, 0 ≤ M ≤ 1000). Then, there are N numbers in the next 2 to N + 1 lines. Input are terminated by EOF.

## 输出格式 OutputFormat

A single number, meaning the mininum cost to print the article.

5 5
5
9
5
7
5

230

Hdu 3507

## 代码 Code

DP + 斜率优化。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
const int maxn=500005;
int i,j,t,n,m,l,r,k,z,y,x;
int a[maxn],f[maxn],sum[maxn];
deque <int> q;
inline int fracup(int x,int y)
{
return (f[x]+sum[x]*sum[x]-f[y]-sum[y]*sum[y]);
}
inline int fracdown(int x,int y)
{
return (2*(sum[x]-sum[y]));
}
int main()
{
while (scanf("%d%d",&n,&m)!=EOF)
{
sum=f=0;
for (i=1;i<=n;i++) scanf("%d",&a[i]),sum[i]=sum[i-1]+a[i];
q.clear();
q.push_back(0);
for (i=1;i<=n;i++)
{
while (q.size()>1 && fracup(*(q.begin()+1),*(q.begin()))<=sum[i]*fracdown(*(q.begin()+1),*(q.begin()))) q.pop_front();
t=q.front();
f[i]=f[t]+(sum[i]-sum[t])*(sum[i]-sum[t])+m;
while (q.size()>1 && fracup(i,*(q.end()-1))*fracdown(*(q.end()-1),*(q.end()-2))<=fracup(*(q.end()-1),*(q.end()-2))*fracdown(i,*(q.end()-1))) q.pop_back();
q.push_back(i);
}
printf("%d\n",f[n]);
}
return 0;
}