HNOI2008玩具装箱(T_OY)bzoj1010

//斜率优化DP,详情看程序
#include<cctype>
#include<cstdio>
#include<map>
#include<cmath>
#include<queue>
#include<vector>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<algorithm>
#define inf 1000000000
#define LL long long
using namespace std;
LL read()
{
    LL x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int n,L,h,t;
int c[50005],q[50005];
LL s[50005],f[50005],C;

double calc(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()
{
	n=read();L=read();C=L+1;
	for(int i=1;i<=n;i++)c[i]=read();
	for(int i=1;i<=n;i++)s[i]=s[i-1]+c[i];
	for(int i=1;i<=n;i++)s[i]+=i;
	h=1;t=0;q[++t]=0;
	for(int i=1;i<=n;i++)
	{
		while(h<t && calc(q[h],q[h+1])<=s[i])h++;
		int k=q[h];
		f[i]=f[k]+(s[i]-s[k]-C)*(s[i]-s[k]-C);
		while(h<t&&calc(q[t],i)<calc(q[t-1],q[t]))t--;
		q[++t]=i;
	}
	printf("%lld\n",f[n]);
	return 0;
}

你可能感兴趣的:(dp)