hdu 3507 Print Article(斜率优化DP)

Print Article

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


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
hdu 3507 Print Article(斜率优化DP)_第1张图片

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
 

Author
Xnozero
 

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

Recommend
zhengfeng   |   We have carefully selected several similar problems for you:   3506  3501  3504  3505  3498 
 

Statistic |  Submit |  Discuss | Note

题目大意:多组数据。每组数据n,m ,n 表示有n个数,m是一个常数。

输出N个数字a[N],输出的时候可以连续连续的输出,每连续输出一串,它的费用是 “这串数字和的平方加上一个常数M”。

题解:斜率优化dp

设f[i]表示输出到i的时候最少的花费,sum[i]表示从a[1]到a[i]的数字和。于是方程就是:

f[i]=f[j]+M+(sum[i]-sum[j])^2;

假设k

把式子拆开,得到f[j]+M+sum[i]^2+sum[j]^2-2sum[i]sum[j]<f[k]+M+sum[i]^2+sum[k]^2-2sum[i]sum[k]

两边移项一下,得到:(f[j]+sum[j]^2-(f[k]+sum[k]^2))/(2*(sum[j]-sum[k]))

就得到了yj-yk/xj-xk

j的决策比k的决策要更优


斜率优化做法总结如下:

1,用一个单调队列来维护解集。

2,假设队列中从头到尾已经有元素a b c。那么当d要入队的时候,我们维护队列的上凸性质,即如果g[d,c]=g[x,y]为止,并将d点加入在该位置中。

3,求解时候,从队头开始,如果已有元素a b c,当i点要求解时,如果g[b,a]

#include
#include
#include
#include
#include
#define N 500003
using namespace std;
int n,m,q[N],a[N],sum[N],f[N];
int y(int x,int y)
{
	return f[y]-f[x]+sum[y]*sum[y]-sum[x]*sum[x];
}
int x(int x,int y)
{
	return sum[y]-sum[x];
}
int main()
{
	 while (scanf("%d%d",&n,&m)!=EOF)
	  {
	  	memset(sum,0,sizeof(sum));
	  	memset(f,0,sizeof(f));
	  	for (int i=1;i<=n;i++)
		  {
		  	scanf("%d",&a[i]);
		  	sum[i]=sum[i-1]+a[i];
		  } 
		int head=0,tail=0; 
		for (int i=1;i<=n;i++)
		{
			int k=2*sum[i];
			while (head=y(q[tail],i)*x(q[tail-1],q[tail]))
			 tail--;
			tail++; q[tail]=i;
		}
		printf("%d\n",f[n]);
	  }
	 return 0;
}



你可能感兴趣的:(动态规划)