2019.01.27-bzoj3156: 防御准备
题目描述:
算法标签:斜率优化
以下代码:
#include<bits/stdc++.h> #define il inline #define LL long long #define db double #define _(d) while(d(isdigit(ch=getchar()))) using namespace std; const int N=1e6+5; int n,a[N],q[N],l,r;LL f[N]; il int read(){ int x,f=1;char ch; _(!)ch=='-'?f=-1:f;x=ch^48; _()x=(x<<1)+(x<<3)+(ch^48); return f*x; } il LL Y(int x){ return 2ll*f[x]+1ll*x*x+(LL)x; } il db K(int a,int b){ return (db)(Y(a)-Y(b))/(db)(a-b); } int main() { n=read(); for(int i=1;i<=n;i++)a[i]=read(); for(int i=1;i<=n;i++){ while(l<r&&K(q[l],q[l+1])<2*i)l++; int j=q[l]; f[i]=f[j]+1ll*(i-j)*(i-j-1)/2ll+(LL)a[i]; while(l<r&&K(i,q[r])<=K(q[r-1],q[r]))r--; q[++r]=i; } printf("%lld\n",f[n]); return 0; }