hdu3507(print article)- 线性dp+斜率优化

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
Monkey Party

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

题目链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值