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 costM 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.
一眼就看出来要用动态规划。
dp[i]表示到i为止的最小费用,朴素的状态转移方程为dp[i]=max{dp[j]+(s[i]-s[j])^2+m},其中s为前缀和数组。
因为有s[i]*s[j]的交叉项,考虑斜率优化。
设目前正在考虑i,对于j>k,j比k优的条件是
dp[j]+(s[i]-s[j])^2+m< dp[k]+(s[i]-s[k])^2+m
记f(i)=dp[i]+s[i]^2,g(i)=2*s[i]
化简得s[i]>(f(j)-f(k))/(g(j)-g(k))
维护一个斜率递增的下凸壳即可。
对于每个i,操作顺序如下:
1.如果次队首比队首优,队首出队。
2.取队首为解。
3.如果插入后不满足下凸壳性质,队尾出队。
4.插入到队尾。
#include<cstdio>
#include<cstring>
#define L long long
L dp[500010],s[500010];
int q[500010];
L f(int x)
{
return dp[x]+s[x]*s[x];
}
L g(int x)
{
return 2*s[x];
}
int main()
{
int i,j,k,m,n,p,hd,tl;
L x,y,z;
while (scanf("%d%d",&n,&m)==2)
{
q[1]=0;
for (i=1;i<=n;i++)
{
scanf("%d",&p);
s[i]=s[i-1]+p;
}
hd=0;
tl=1;
for (i=1;i<=n;i++)
{
while (tl>hd&&
(g(q[hd+1])-g(q[hd]))*s[i]>
f(q[hd+1])-f(q[hd]))
hd++;
dp[i]=dp[q[hd]]+(s[i]-s[q[hd]])*(s[i]-s[q[hd]])+m;
while (tl>hd&&
(f(q[tl])-f(q[tl-1]))*(g(i)-g(q[tl]))>=
(g(q[tl])-g(q[tl-1]))*(f(i)-f(q[tl])))
tl--;
q[++tl]=i;
}
printf("%lld\n",dp[n]);
}
}

本文介绍了一个使用动态规划解决的文章打印成本最小化问题。通过斜率优化的方法,有效地减少了状态转移的时间复杂度,实现了一种高效的求解算法。
1081

被折叠的 条评论
为什么被折叠?



