[bzoj4518][Sdoi2016]征途【dp】
【题目链接】
http://www.lydsy.com/JudgeOnline/problem.php?id=4518
【题解】
斜率优化dp。
首先不难想到一个的暴力,由于平均值是固定的,记表示到了第站,停了次的方差最小值,
将这东西展开,就能得到比优的条件:
时,比优。
/* --------------
user Vanisher
problem bzoj-4518
----------------*/
# include <bits/stdc++.h>
# define ll long long
# define inf 0x3f3f3f3f
# define N 3010
# define eps 1e-9
using namespace std;
ll read(){
ll tmp=0, fh=1; char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') fh=-1; ch=getchar();}
while (ch>='0'&&ch<='9'){tmp=tmp*10+ch-'0'; ch=getchar();}
return tmp*fh;
}
ll sqr(ll x){
return x*x;
}
ll n,m,a[N],s[N],f[N][N],st[N];
double slope(ll j, ll k, ll t){
double up=f[j][t]+m*m*s[j]*s[j]+2*m*s[j]*s[n]-f[k][t]-m*m*s[k]*s[k]-2*m*s[k]*s[n],
down=2*m*m*(s[j]-s[k]);
return up/down;
}
int main(){
n=read(), m=read();
for (ll i=1; i<=n; i++)
a[i]=read(), s[i]=s[i-1]+a[i];
memset(f,inf,sizeof(f));
f[0][0]=1;
for (ll t=1; t<=m; t++){
ll pl=1, pr=0;
for (ll i=1; i<=n; i++){
while (pl<pr&&slope(i-1,st[pr],t-1)<=slope(st[pr],st[pr-1],t-1)+eps) pr--;
st[++pr]=i-1;
while (pl<pr&&slope(st[pl+1],st[pl],t-1)<=s[i]+eps) pl++;
f[i][t]=f[st[pl]][t-1]+sqr(s[i]-s[st[pl]])*m*m-2*(s[i]-s[st[pl]])*s[n]*m+s[n]*s[n];
}
//f[i][t]=min(f[i][t],f[j][t-1]+sqr(s[i]-s[j])*m*m-2*(s[i]-s[j])*s[n]*m+s[n]*s[n]);
}
printf("%lld\n",f[n][m]/m);
return 0;
}