【HDU 3507】Print Article(斜率优化dp)
Print Article
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 8583 Accepted Submission(s): 2673
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
Author
Xnozero
Source
2010 ACM-ICPC Multi-University Training Contest(7)——Host by HIT
【题解】【斜率优化dp】
首先根据题意,设dp[i]表示输出到i的时候最少的花费,sum[i]表示从a[1]到a[i]的数字和,则转移方程为:**f[i]=f[j]+m+
然而,500000,woc,明显会超时啊!
加优化吧——斜率优化(窝也是第一次写哈)
假设k
两边移项一下,得到:
那么不就是yj-yk/xj-xk
那么yj-yk/xj-xk
关键的来了:现在从左到右,还是设k
我们假设g[i,j]
如果g[i,j]>=sum[i],那么j点此时是比i点要更优,但是同时g[j,k]>g[i,j]>sum[i]。这说明还有k点会比j点更优,同样排除j点。
排除多余的点,这便是一种优化!
接下来看看如何找最优解。
设k
这样,从左到右,斜率之间就是单调递减的了。当我们的最优解取得在j点的时候,那么k点不可能再取得比j点更优的解了,于是k点也可以排除。换句话说,j点之前的点全部不可能再比j点更优了,可以全部从解集中排除。
于是对于这题我们对于斜率优化做法可以总结如下:
1)用一个单调队列来维护解集。
2)假设队列中从头到尾已经有元素a b c。那么当d要入队的时候,我们维护队列的上凸性质,即如果g[d,c]
3)求解时候,从队头开始,如果已有元素a b c,当i点要求解时,如果g[b,a]
(自:http://www.cnblogs.com/ka200812/archive/2012/08/03/2621345.html)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m;
int sum[500010],f[500010],q[500010],h,t;
int getdp(int i,int j)
{
return f[j]+m+(sum[i]-sum[j])*(sum[i]-sum[j]);
}
int getup(int j,int k)//yj-yk的部分
{
return f[j]+sum[j]*sum[j]-(f[k]+sum[k]*sum[k]);
}
int getdown(int j,int k)
{
return 2*(sum[j]-sum[k]);
}
int main()
{
int i,j;
while((scanf("%d%d",&n,&m)==2))
{
for(i=1;i<=n;++i) scanf("%d",&sum[i]);
sum[0]=f[0]=0;
for(i=1;i<=n;++i) sum[i]+=sum[i-1];
h=t=0; q[t++]=0;
for(i=1;i<=n;++i)
{
while(h+1<t && getup(q[h+1],q[h])<=sum[i]*getdown(q[h+1],q[h])) h++;
f[i]=getdp(i,q[h]);
while(h+1<t && getup(i,q[t-1])*getdown(q[t-1],q[t-2])<=getup(q[t-1],q[t-2])*getdown(i,q[t-1])) t--;
q[t++]=i;
}
printf("%d\n",f[n]);
}
return 0;
}