斜率优化实现初步(7) [BZOJ][4518][Sdoi2016]征途
#include<bits/stdc++.h> using namespace std; //#define int long long const int MAXN=3e3+233; int n,m,all; int a[MAXN],sum[MAXN]; int f[MAXN][MAXN],g[MAXN][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,int opt){ return (g[opt][j]-g[opt][k])/(sum[j]-sum[k]); } int pow2(int x){ return x*x; } signed main(){ n=read(),m=read(); for (int i=1;i<=n;i++){ a[i]=read(),sum[i]=sum[i-1]+a[i]; f[1][i]=pow2(sum[i]),g[1][i]=f[1][i]+pow2(sum[i]); } all=sum[n]; for (int opt=2;opt<=m;opt++){ head=1,tail=1,q[head]=opt-1; for (int i=opt;i<=n;i++){ while (head<tail&&slope(q[head+1],q[head],opt-1)<2*sum[i]) head++; f[opt][i]=f[opt-1][q[head]]+pow2(sum[i]-sum[q[head]]); g[opt][i]=f[opt][i]+pow2(sum[i]); while (head<tail&&slope(i,q[tail],opt-1)<slope(q[tail],q[tail-1],opt-1)) tail--; q[++tail]=i; } } printf("%d\n",f[m][n]*m-all*all); return 0; }