最近学了学斜率dp,刷了几道题,感觉挺不错。
题目
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)(0 ≤ N ≤ 500000, 0 ≤ M ≤ 1000)(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
题目大意
给定 NNN 个长度为 CiC_iCi 的单词,要求在若干个单词放在一行的花费如题,求最小花费。
题解&思路
比较明显地,这题需要用动态规划来完成。
我们设 fif_ifi 表示第 iii 个单词为一行某尾的最小花费。
我们考虑如何转移。
因为当前的 iii 为一行某尾,所以,我们可以找到一个 jjj 为上一行某尾,再加上当前这一行的代价。
如此便十分明显了:
我们设 SiS_iSi 表示 ∑j=1iCj\sum_{j=1}^{i} C_j∑j=1iCj 的和
状态转移方程如下:
fi=min(fj+(Si−Sj)2+M)f_i=min(f_j+(S_i-S_j)^2+M)fi=min(fj+(Si−Sj)2+M)
但是由于 0≤N≤5000000 ≤ N ≤ 5000000≤N≤500000 ,如此 O(N2)O(N^2)O(N2) 的转移的时间让人难以接受,所以我们考虑优化。
看到 minminmin , 中间的乘积,很容易会想到斜率优化dp。
若我们想要 jjj 比 kkk 优,那么我们需要满足:
fj+(Si−Sj)2+M<fk+(Si−Sk)2+Mf_j+(S_i-S_j)^2+M<f_k+(S_i-S_k)^2+Mfj+(Si−Sj)2+M<fk+(Si−Sk)2+M
化简一下:
fj+(Si)2−2SiSj+(Sj)2+M<fk+(Si)2−2SiSk+(Sk)2+Mf_j+(S_i)^2-2 S_iS_j+(S_j)^2+M<f_k+(S_i)^2-2 S_iS_k+(S_k)^2+Mfj+(Si)2−2SiSj+(Sj)2+M<fk+(Si)2−2SiSk+(Sk)2+M
(fj+(Sj)2)−(fk+(Sk)2)Sj−Sk<2Si\frac{(f_j+(Sj)^2)-(f_k+(S_k)^2)}{S_j-S_k}<2S_iSj−Sk(fj+(Sj)2)−(fk+(Sk)2)<2Si(脑补中间化简过程)
于是乎,对于一个点 jjj 其坐标就为 (Sj,fj+(Sj)2)(S_j,f_j+(S_j)^2)(Sj,fj+(Sj)2)
因为这是去 minminmin ,所以我们就可以愉快地用单调队列维护一个下凸包了。
CodeCodeCode
#include<cstdio>
#define ll long long
#define fo(i,a,b) for(int i=a;i<=b;++i)
using namespace std;
const int N=500005;
ll m;
int n,h,t;
int d[N];
ll s[N],a[N],f[N];
double X(int x){
return s[x];
}
double Y(int x){
return f[x]+s[x]*s[x];
}
double slope(int i,int j){
if (X(i)==X(j)) return (Y(j)-Y(i))/(1e-18);
return (Y(j)-Y(i))/(X(j)-X(i));
}
int main(){
while (~scanf("%d%lld",&n,&m)){
s[0]=0;
f[0]=0;
fo(i,1,n){
scanf("%lld",&a[i]);
s[i]=s[i-1]+a[i];
d[i]=0;
}
h=1;t=1;
d[1]=0;
fo(i,1,n){
while (h<t&&slope(d[h],d[h+1])<=2*s[i]) ++h;
int j=d[h];
f[i]=f[j]+(s[i]-s[j])*(s[i]-s[j])+m;
while (h<t&&slope(d[t-1],d[t])>=slope(d[t-1],i)) --t;
d[++t]=i;
}
printf("%lld\n",f[n]);
}
return 0;
}
312

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



