1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #include <iostream> #include <cstring> #include <algorithm> using namespace std;
typedef long long LL; const int N = 500010; int n,m,q[N]; LL s[N],f[N];
double slope(int i,int j){ return (double)(f[i]+s[i]*s[i]-f[j]-s[j]*s[j]) /(s[i]==s[j]?1e-9:s[i]-s[j]); } int main(){ while(~scanf("%d%d",&n,&m)){ for(int i=1;i<=n;i++) scanf("%lld",&s[i]),s[i]+=s[i-1]; int h=1,t=0; for(int i=1;i<=n;i++){ while(h<t && slope(i-1,q[t])<=slope(q[t],q[t-1])) t--; q[++t]=i-1; while(h<t && slope(q[h+1],q[h])<=2*s[i]) h++; int j=q[h]; f[i]=f[j]+(s[i]-s[j])*(s[i]-s[j])+m; } printf("%lld\n",f[n]); } }
|