Print Article HDU 3507(斜率DP入门模板题)

来源:互联网 发布:linux eagle监控软件 编辑:程序博客网 时间:2024/06/05 06:19

Print Article

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


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 559575
 

Sample Output
230
 

Author
Xnozero
 

Source
2010 ACM-ICPC Multi-University Training Contest(7)——Host by HIT

分析:首先纯暴力是肯定不行的。因为其状态转移方程为:dp[i]=dp[j]+M+(sum[i]-sum[j])^2;其中dp[i]表示输出到i的时候最少的花费,sum[i]表示从a[1]到a[i]的数字和。所以会想到斜率优化。

详见  http://www.cnblogs.com/ka200812/archive/2012/08/03/2621345.html

代码如下:

/* Author:kzl */#include<iostream>#include<cstring>#include<algorithm>#include<cstdio>using namespace std;const int maxx = 500000+500;int n,m;int dp[maxx],sum[maxx],q[maxx];int aa;int getup(int i,int j){    return dp[i] - dp[j] + sum[i] * sum[i] - sum[j] * sum[j];}int getdown(int i,int j){return 2*(sum[i] - sum[j]);}int getdp(int i,int j){    return dp[j] + (sum[i] - sum[j])*(sum[i] - sum[j]) + m;}int main(){    sum[0] = 0;while(scanf("%d%d",&n,&m)!=EOF){    for(int i=1;i<=n;i++){    scanf("%d",&aa);    sum[i] = sum[i-1] + aa;    }    dp[0] = 0;    int head = 0;    int tail = 0;    q[tail++] = 0;    for(int i=1;i<=n;i++){        while(head+1<tail && getup(q[head+1],q[head])<sum[i]*getdown(q[head+1],q[head])){            head++;        }        dp[i] = getdp(i,q[head]);         while(head+1<tail && getup(i,q[tail-1])*getdown(q[tail-1],q[tail-2]) <= getup(q[tail-1],q[tail-2])*getdown(i,q[tail-1])){            tail--;         }         q[tail++] = i;    }    printf("%d\n",dp[n]);}return 0;}


原创粉丝点击