APIO2010特别行动队bzoj1911

//斜率优化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
#define sqr(x) ((x)*(x))
#define check(j,k,i) ((f[j]-f[k]+a*(sqr(s[j])-sqr(s[k]))>=(a*s[i]*(s[j]-s[k])<<1)))
#define cmp(j,k,i) ((f[j]-f[k]+a*(sqr(s[j])-sqr(s[k])))*(s[k]-s[i])>=(f[k]-f[i]+a*(sqr(s[k])-sqr(s[i])))*(s[j]-s[k]))
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;
}
LL s[1000010],f[1000010];
int q[1000010];
int n,h,r;
LL  a,b,c;

int main()
{
        n=read();a=read();b=read();c=read();
        for (int i=1;i<n+1;++i)
                (s[i]=read())+=s[i-1];
        f[0]=0;h=0,r=1;
        for (int i=1;i<n+1;i++)
        {
                while (h<r-1 && !check(q[h],q[h+1],i))++h;
                f[i]=f[q[h]]+a*sqr(s[i]-s[q[h]])+c;
                while (h<r-1 && !cmp(q[r-2],q[r-1],i))--r;
                q[r++]=i;
        }
        printf("%lld\n",f[n]+b*s[n]);
        return 0;
}

你可能感兴趣的:(dp)