HDU Print Article

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.

题目大意:

Zero有一个打印机,他喜欢用它来打印文章。
一天Zero想打印一篇有n个字的
文章,每个单词有一个Ci印刷成本。同时,Zero知道将第i~j个打印在一行中将花费{∑(k=i~j)c[k]}^2+M的成本。其中M是一个常量。现在Zero想知道打印这篇文章的最低成本。

输入有多组数据

第一行为n,M,接下来n行表示c[i]。输入以输入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

题解

这是我第一次用斜率优化做的题。以下是我的理解:
主要思路是:用sum[i]表示从1~i个字c[i]的前缀和。则基本方程是:f[i]=min(f[j]+(sum[i]-sum[j])^2+M)。
假设现在要处理第i个字,设k<j<i,且j比k优,则可得式子:f[k]+(sum[i]-sum[k])^2+M<=f[j]+(sum[i]-sum[j])^2+M.化简可得
{ (f[j]+sum[j]^2)-(f[k]+sum[k]^2) / { 2*sum[j]-2*sum[k] } <=sum[i]。………………等式1
通过这个式子就可将“决策指针”定位。

接下来是将i加入表示决策的单调队列,设xj=f[j]+sum[j]^2; xk=f[k]+sum[k]^2;  yj=2*sum[j]; yk=2*sum[k];
则等式1的左边表示为(xj-xk)/(yj-yk),这个式子就是斜率,因为sum递增,所以我们要维护的是一个下凸包。所以对于一个新加入的决策i,这要保证斜率递增即可。

由于写的时候还不是特别理解,所以函数名可能有点怪。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int n,m,a[500002],sum[500002];
int q[500002],f[500002];
int hanshu(int k,int j)
{return f[j]+sum[j]*sum[j]-(f[k]+sum[k]*sum[k]);}
int down(int k,int j)
{return 2*(sum[j]-sum[k]);}
void doit()
{
	int t=1,w=1;
	for(int i=1;i<=n;i++)
	   {while(t<w&&hanshu(q[t],q[t+1])<=sum[i]*down(q[t],q[t+1]))//选择最优决策 
		   t++;
		int p=q[t];
        f[i]=f[p]+(sum[i]-sum[p])*(sum[i]-sum[p])+m;
        while(t<w&&hanshu(q[w],i)*down(q[w-1],q[w])<=hanshu(q[w-1],q[w])*down(q[w],i))
           w--;//维护凸包 
        q[++w]=i;
        }
}
int main()
{
	while(scanf("%d%d",&n,&m)!=EOF)
	   {for(int i=1;i<=n;i++)
	       {scanf("%d",&a[i]); sum[i]=sum[i-1]+a[i];}
	    doit();
	    printf("%d\n",f[n]);
	   }
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值