[斜率优化 DP] BZOJ 4518 [Sdoi2016]征途

就是求平方和的最小值

然后就是裸的斜率优化了


#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;

inline char nc()
{
	static char buf[100000],*p1=buf,*p2=buf;
	if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; } 
	return *p1++;
}

inline void read(ll &x)
{
	char c=nc(),b=1;
	for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
	for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=30005;

ll ans,m,n,t;
ll f[2][N],s[N],a[N];

ll Q[N],l,r;

inline double K(int i,int j)
{
	return (double)(f[t][i]+s[i]*s[i]-f[t][j]-s[j]*s[j])/(s[i]-s[j]);
}

int main()
{
	freopen("t.in","r",stdin);
	freopen("t.out","w",stdout);
	read(n); read(m);
	for (int i=1;i<=n;i++) read(a[i]),s[i]=s[i-1]+a[i];
	for (int i=1;i<=n;i++) f[t][i]=s[i]*s[i];
	for (int j=2;j<=m;j++,t^=1)
	{
		l=1,r=0;
		for (int i=1;i<=n;i++)
		{
			while (r>l && K(Q[r],i)<K(Q[r-1],Q[r])) r--;
			Q[++r]=i;
			while (r>l && K(Q[l],Q[l+1])<2*s[i]) l++;
			f[t^1][i]=f[t][Q[l]]+(s[i]-s[Q[l]])*(s[i]-s[Q[l]]);
		}
	}
	printf("%lld\n",m*f[t][n]-s[n]*s[n]);
	return 0;
}


你可能感兴趣的:([斜率优化 DP] BZOJ 4518 [Sdoi2016]征途)