Print Article
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 11610 Accepted Submission(s): 3544
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.
Input
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.
Output
A single number, meaning the mininum cost to print the article.
Sample Input
5 5
5
9
5
7
5
Sample Output
230
【分析】
斜率优化dp的小水(难)题
大概题意就是要输出N个数字a[N],输出的时候可以连续连续的输出,每连续输出一串,它的费用是 “这串数字和的平方加上一个常数M”。
这题的做法可以参考 bzoj 1010 玩具装箱toy
另外,这道题有坑点,注意一串0连续排列的情况。
【代码】
//hdu 3507 Print Article
#include<iostream>
#include<cstring>
#include<cstdio>
#define ll long long
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int mxn=500005;
ll n,m;
ll dp[mxn],sum[mxn],c[mxn],q[mxn];
inline ll get(ll left,ll rig)
{
ll up=dp[left-1]-dp[rig-1]+sum[left-1]*sum[left-1]-sum[rig-1]*sum[rig-1];
ll down=2*(sum[left-1]-sum[rig-1]);
if(!down) return dp[n+1];
return up/down;
}
int main()
{
ll i,j,calc,h,t;
while(scanf("%lld%lld",&n,&m)!=EOF)
{
memset(dp,0x7f7f,sizeof dp);
dp[0]=0;
fo(i,1,n) scanf("%lld",&c[i]);
fo(i,1,n) sum[i]=sum[i-1]+c[i];
h=1,t=0;
fo(i,1,n)
{
while(h<t && get(q[h],q[h+1])<sum[i]) h++;
ll now=q[h];if(!now) now=1;
dp[i]=dp[i-1]+c[i]*c[i]+m;
dp[i]=min(dp[i],dp[now-1]+(sum[i]-sum[now-1])*(sum[i]-sum[now-1])+m);
while(h<t && get(q[t-1],q[t])>get(q[t],i)) t--;
q[++t]=i;
}
printf("%lld\n",dp[n]);
}
return 0;
}