Print Article

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 4990    Accepted Submission(s): 1509


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
 
 
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <algorithm>
 4 #include <string.h>
 5 #include <set>
 6 using namespace std;
 7 int a[600000],sum[600000],h[600000],dp[600000],m;
 8 int getup(int j,int k)
 9 {
10     return dp[j]+sum[j]*sum[j]-dp[k]-sum[k]*sum[k];
11 }
12 int getdown(int j,int k)
13 {
14     return ((sum[j]-sum[k])<<1);
15 }
16 int getdp(int i,int j)
17 {
18     return dp[j]+m+(sum[i]-sum[j])*(sum[i]-sum[j]);
19 }
20 int main()
21 {
22     int n,i,head,tail;
23     while(~scanf("%d%d",&n,&m))
24     {
25         memset(h,0,sizeof(h));
26         sum[0]=a[0]=0;
27         for(i=1; i<=n; i++)
28             scanf("%d",&a[i]),sum[i]=sum[i-1]+a[i];
29             head=tail=0;
30             h[tail++]=0;
31         for(i=1;i<=n;i++)
32         {
33             while(head+1<tail&&getup(h[head+1],h[head])<=sum[i]*getdown(h[head+1],h[head]))
34             head++;
35             dp[i]=getdp(i,h[head]);
36             while(head+1<tail&&getup(h[tail-1],h[tail-2])*getdown(i,h[tail-1])>=getup(i,h[tail-1])*getdown(h[tail-1],h[tail-2]))
37             tail--;
38             h[tail++]=i;
39         }
40         cout<<dp[i-1]<<endl;
41     }
42 }
View Code

 

posted on 2014-07-09 15:02  ERKE  阅读(302)  评论(0编辑  收藏  举报