BZOJ1911: [Apio2010]特别行动队

题目描述:传送门

题解:

斜率优化DP。
f[i]=f[j]+a*(s[i]-s[j])^2+b*(s[i]-s[j])+c
f[i]+2*a*s[i]*s[j]=f[j]+a*s[j]^2-b*s[j]+(a*s[i]^2+b*s[i]+c)
b + k x = y

代码如下:

#include<cstdio>
#include<string>
using namespace std;
const int maxn=1000005;
int n,a,b,c,que[maxn];
long long s[maxn],f[maxn];
inline int read(){
    int x=0,flg=1; char ch=getchar();
    while (ch<'0'||ch>'9') {if (ch=='-') flg=-1; ch=getchar();}
    while (ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
    return flg*x;
}
double X(int x) {return 1.0*s[x];}
double Y(int x) {return 1.0*f[x]+a*s[x]*s[x]-b*s[x];}
double xl(int y,int x) {return (Y(x)-Y(y))/(X(x)-X(y));}
int main(){
    n=read(),a=read(),b=read(),c=read();
    for (int i=1;i<=n;i++) s[i]=1ll*read(),s[i]+=s[i-1];
    int head=0,tail=0;
    for (int i=1;i<=n;i++){
        while (head<tail&&xl(que[head],que[head+1])>2*a*s[i]) head++;
        int j=que[head]; f[i]=f[j]+a*(s[i]-s[j])*(s[i]-s[j])+b*(s[i]-s[j])+c;
        while (head<tail&&xl(que[tail-1],que[tail])<xl(que[tail],i)) tail--;
        que[++tail]=i;
    }
    printf("%lld\n",f[n]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dyt_b/article/details/79393606