斜率优化实现初步(1) [BZOJ][1010][HNOI2008]玩具装箱toy

#include<bits/stdc++.h>
using namespace std;

#define int long long
const int MAXN=5e4+2333;

int n,L,C;
int a[MAXN],pre[MAXN];
int head=1,tail=1,q[MAXN];
int f[MAXN],g[MAXN];
/*
    f[i]=min(f[j]+(pre[i]-pre[j]+i-j-1-L)^2)
    -> g[i]=pre[i]+i   C=L+1
    -> slope(i,j) = ((f[j]-f[k])/(g[j]-g[k])+g[j]+g[k]+2*C)
    -> as for i , j is better than k if and only if slope(j,k)<=2*g[i]
    -> i is better when slope(i,j)<slope(j,k)
*/

int read(){
    int x=0,f=1;char ch=getchar();
    while (!isdigit(ch)) { if (ch=='-') f=-1; ch=getchar();}
    while (isdigit(ch)) x=x*10+ch-48,ch=getchar();
    return x*f;
}

int slope(int j,int k){
    return (1.0*(f[j]-f[k])/(g[j]-g[k])+g[j]+g[k]+2.0*C);
}

int pow2(int x){
    return x*x;
}

signed main(){
    n=read(),L=read(),C=L+1;
    for (int i=1;i<=n;i++)
        a[i]=read(),pre[i]=pre[i-1]+a[i];
    for (int i=1;i<=n;i++){
        g[i]=pre[i]+i;
        while (head<tail&&slope(q[head+1],q[head])<=2*g[i])
            head++;
        f[i]=f[q[head]]+pow2(g[i]-g[q[head]]-C);
        while (head<tail&&slope(i,q[tail])<slope(q[tail],q[tail-1]))
            tail--;
        q[++tail]=i;
    }
    printf("%lld\n",f[n]);
    return 0;
}

 

posted @ 2018-08-25 10:34  QingCai_DCF  阅读(125)  评论(0编辑  收藏  举报