[BZOJ1911][Apio2010]特别行动队(斜率优化dp)

题目描述

传送门

题解

转移方程: fi=max{fj+a(sisj)2+b(sisj)+c}j<i 其中s表示前缀和
很显然的斜率优化。

代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define LL long long

const int max_n=1e6+5;

int n,a,b,c,x,head,tail;
int q[max_n];
LL s[max_n],f[max_n];

inline LL K(int j){return (LL)-2*a*s[j];}
inline LL B(int j){return (LL)f[j]+a*s[j]*s[j]-b*s[j];}
inline LL Y(int i,int j){return (LL)K(j)*s[i]+B(j);}
inline bool cmp(int x1,int x2,int x3){
    LL w1=(K(x1)-K(x3))*(B(x2)-B(x1));
    LL w2=(K(x1)-K(x2))*(B(x3)-B(x1));
    return w1>=w2;
}

int main(){
    scanf("%d",&n); scanf("%d%d%d",&a,&b,&c);
    for (int i=1;i<=n;++i) scanf("%d",&x),s[i]=s[i-1]+x;
    head=tail=0;
    for (int i=1;i<=n;++i){
        while (head<tail&&Y(i,q[head])<=Y(i,q[head+1])) head++;
        f[i]=(LL)Y(i,q[head])+a*s[i]*s[i]+b*s[i]+c;
        while (head<tail&&cmp(i,q[tail-1],q[tail])) tail--;
        q[++tail]=i;
    }
    printf("%lld\n",f[n]);
}

你可能感兴趣的:(dp,apio,bzoj)