您的位置:首页 > 编程语言 > C语言/C++

c++之路进阶——斜率优化形如DP[i]=f[j]+x[i](f[j]只与j变量有关)的问题(Print Article)

2016-01-24 17:43 543 查看
参考博文:/article/6002672.html//讲的真的很好,有个小错误,博客里的num全为sum,像我这种弱渣都听懂了。真心点赞!!!

Print Article

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


[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
A single number, meaning the mininum cost to print the article.

[align=left]Sample Input[/align]

5 5
5
9
5
7
5

[align=left]Sample Output[/align]

230

[align=left]Author[/align]
[align=left] [/align]
Xnozero

[align=left]Source[/align]
[align=left]解释: [/align]



[align=left] [/align]



[align=left] 题解:[/align]
1,用一个单调队列来维护解集。
2,假设队列中从头到尾已经有元素a b c。那么当d要入队的时候,我们维护队列的上凸性质,即如果g[d,c]<g[c,b],那么就将c点删除。直到找到g[d,x]>=g[x,y]为止,并将d点加入在 该位置中。

3,求解时候,从队头开始,如果已有元素a b c,当i点要求解时,如果g[b,a]<sum[i],那么说明b点比a点更优,a点可以排除,于是a出队。最后dp[i]=getDp(q[head])。

代码:

#include<cstdio>
#include<cmath>
#include<iostream>
#define maxn 500100

using namespace std;

struct get
{
int n,m,sum[maxn],a[maxn],dp[maxn],q[maxn];
int getup(int j,int k){return dp[j]+sum[j]*sum[j]-dp[k]-sum[k]*sum[k];}//分子
int getdown(int j,int k){return 2*sum[j]-2*sum[k];}//分母
int getdp(int i,int j) {return dp[j]+m+(sum[i]-sum[j])*(sum[i]-sum[j]);}//dp[i]
get()
{
while (scanf("%d%d",&n,&m)==2)
{
for(int i=1;i<=n;i++) scanf("%d",&sum[i]);
sum[0]=dp[0]=0;
for(int i=1;i<=n;i++)sum[i]+=sum[i-1];
int  t=0,w=1;
for (int i=1;i<=n;i++)
{
while (t+1<w&&sum[i]*getdown(q[t+1],q[t])>=getup(q[t+1],q[t])) t++;//维护队列,删除就点之前所有点
dp[i]=getdp(i,q[t]);
while (t+1<w&&getup(i,q[w-1])*getdown(q[w-1],q[w-2])<=getup(q[w-1],q[w-2])*getdown(i,q[w-1])) w--;//维护队列,保证队列具有 上凸性质。
q[w++]=i;
}
printf("%d\n",dp
);
}
}
}get;
int main()
{
get;
return 0;
}


顺便吐槽一下,

Presentation Error 这种错误你们见过么?我也是醉了!

[align=left]Recommend[/align]
zhengfeng | We have carefully selected several similar problems for you: 3506 3501 3504 3505 3498
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: