Print Article
问题描述 :
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.
输入:
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.
输出:
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.
样例输入:
5 5
5
9
5
7
5
样例输出:
230
Print Article
问题描述 :
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
![Monkey Party](http://www.acmerblog.com/img/1397478306823.jpg)
M is a const number.
Now Zero want to know the minimum cost in order to arrange the article perfectly.
输入:
输出:
样例输入:
样例输出:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3507
题目大意:给定一个长度为n的序列,和一个常数m,我们可以将序列分成随意段,每段的权值为sum(arr[i]) + C(x<=i<=y),求一种划分方法使得整个序列的权值最小.n<=50万。
解题思路:做完Hdu的2829,然后再看这题,一切变得如此简单,用两种方法解。
状态转移方程为: dp[i] = min(dp[j] + (sum[i]-sum[j])^2 + m) (j < i);
方法一:dp[i] = dp[j] + (sum[i]-sum[j])^2 + m = dp[j] + sum[i] * sum[i] + sum[j] * sum[j] – 2 * sum[i] * sum[j] + m;
设y = dp[j] + sum[j] * sum[j],x = sum[j],那么原式等于:dp[i] = y + 2 * sum[i] * x + m + sum[i] * sum[i],然后套下斜率优化DP模板即可ac。
方法二:方法二使用的优化技巧类似于四边形不等式,用个s[i] 记录dp[i]由前面的哪个状态转移过来,然后枚举的时候只要枚举s[i-1] 到i-1就可以了。
第二种方法似乎比第一种要慢一些,常数比较大。
#include <stdio.h>
#include <string.h>
#define MAX 501000
int n,m,mi[MAX];
__int64 sum[MAX],sex[MAX];///数组sex[i]用来记录前i个字符的最小花费
int hi[MAX];///数组hi是记录到达上一个字符时分割点的取值
///solve函数用来求解最小值
__int64 Solve() {
__int64 mmin,i = 1;
for (; i <= n; ++i) {
mmin = -1;
for (int j = hi[i-1]; j < i; ++j)
if (mmin == -1 ||sex[j] + (sum[i] - sum[j]) * (sum[i] - sum[j])< mmin)
{
mmin = sex[j] + (sum[i] - sum[j]) * (sum[i] - sum[j]);
hi[i] = j;
}
sex[i] = mmin+m;
}
return sex[n];
}
int main()
{
int i;
while (scanf("%d%d",&n,&m) != EOF) {
/**
在读入数据的同时,用数组的sum[i]记录前面i个数的和
*/
memset(hi,0,sizeof(hi));
memset(sex,0,sizeof(sex));
for (i = 1; i <= n; ++i)
{
scanf("%d",&mi[i] );
sum[i] = mi[i] + sum[i-1];
}
__int64 flag = Solve();
printf("%lld\n",flag);
}
return 0;
}