1、B站视频链接:E51【模板】斜率优化DP 打印文章_哔哩哔哩_bilibili
题目链接:Problem - 3507
cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=500010;
int n,m,q[N];
LL s[N],f[N];
double sl(int i,int j){
return (double)(f[i]+s[i]*s[i]-f[j]-s[j]*s[j])
/(s[i]==s[j]?1e-9:s[i]-s[j]);
}
int main(){
while(~scanf("%d%d",&n,&m)){
for(int i=1;i<=n;i++){
scanf("%lld",&s[i]);
s[i]+=s[i-1];
}
}
int h=1,t=0;
for(int i=1;i<=n;i++){
while(h<t&&sl(i-1,q[t])<=sl(q[t],q[t-1]))t--;
q[++t]=i-1;
while(h<t&&sl(q[h+1],q[h])<=2*s[i])h++;
int j=q[h];
f[i]=f[j]+(s[i]-s[j])*(s[i]-s[j])+m;
}
printf("%lld\n",f[n]);
return 0;
}