hdu3507 Print Article 斜率优化dp

题目链接:戳这里

Print Article

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


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
 

题目大意:有n个数需要输出,每个数的代价是c[i],连续输出一段数的代价是这一段c[i]的和的平方加上一个常数M,求最小代价。

题解:很容易想到dp方程:dp[i]表示输出前i的数的最小代价。

转移:dp[i]=min{dp[j]+(sum[i]-sum[j])^2+M),其中sum[i]表示前缀和,1<=j<=i。

因为转移是n^2复杂度,而n是500000,直接转移无法接受,考虑斜率优化。

设k<j且j比k优,可推得dp[j]+(sum[i]-sum[j])^2+M <= dp[k]+(sum[i]-sum[k])^2+M。

移项化简即可。

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int read()
{
	char c;int sum=0,f=1;c=getchar();
	while(c<'0' || c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0' && c<='9'){sum=sum*10+c-'0';c=getchar();}
	return sum*f;
}
int n,m;
LL sum[500005],dp[500005];
int q[500005],head,tail;
LL sqr(LL x){return x*x;}
LL slop(int j,int k)
{
	return dp[j]+sqr(sum[j])-dp[k]-sqr(sum[k]);
}
LL slop2(int j,int k)
{
	return 2*sum[j]-2*sum[k];
}
int main()
{
	while(scanf("%d%d",&n,&m)==2)
	{
		sum[0]=dp[0]=0;
		for(int x,i=1;i<=n;i++)
		{
			x=read();
			sum[i]=sum[i-1]+x;
		}
		head=tail=0;q[tail++]=0;
		for(int i=1;i<=n;i++)
		{
			while(head+1<tail && slop(q[head+1],q[head])<=sum[i]*slop2(q[head+1],q[head]))
               head++;
            int now=q[head];
            dp[i]=dp[now]+sqr(sum[i]-sum[now])+m;
            while(head+1<tail && slop(i,q[tail-1])*slop2(q[tail-1],q[tail-2])<=slop(q[tail-1],q[tail-2])*slop2(i,q[tail-1]))
            tail--;
            q[tail++]=i;
		}
		printf("%lld\n",dp[n]);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值