题解:

斜率优化dp

f[i]=f[j]+(i-j+sum[i]-sum[j]-L)^2

然后斜率优化

代码:

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=50005;
int n,L,l,r,x,q[N];
ll s[N],f[N],C;
double slop(int j,int k)
{
    return (f[k]-f[j]+(s[k]+C)*(s[k]+C)-(s[j]+C)*(s[j]+C))/(2.0*(s[k]-s[j]));
}
int main()
{
    scanf("%d%d",&n,&L);C=L+1;
    for (int i=1;i<=n;i++)scanf("%d",&x),s[i]=s[i-1]+x+1;
    l=1;r=0;q[++r]=0;
    for (int i=1;i<=n;i++)
     {
        while (l<r&&slop(q[l],q[l+1])<=s[i])l++;
        int t=q[l];
        f[i]=f[t]+(s[i]-s[t]-C)*(s[i]-s[t]-C);
        while (l<r&&slop(q[r],i)<slop(q[r-1],q[r]))r--;
        q[++r]=i;
     }
    printf("%lld\n",f[n]);
    return 0;
}

 

posted on 2018-03-13 21:00  宣毅鸣  阅读(113)  评论(0编辑  收藏  举报