斜率优化实现初步(5) [BZOJ][3156]防御准备

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

#define int long long
const int MAXN=1e6+23333;

int n;
int a[MAXN],sum[MAXN];
int f[MAXN],g[MAXN];
int head=1,tail=1,q[MAXN];

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 (g[j]-g[k])/(j-k);
}

signed main(){
    n=read();
    for (int i=1;i<=n;i++)
        a[i]=read(),sum[i]=sum[i-1]-i;
    for (int i=1;i<=n;i++){
        while (head<tail&&slope(q[head+1],q[head])<i)
            head++;
        f[i]=f[q[head]]+sum[i]-sum[q[head]]+(i-q[head])*i+a[i];
        g[i]=f[i]-sum[i];
        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 20:08  QingCai_DCF  阅读(119)  评论(0编辑  收藏  举报