[bzoj4518][Sdoi2016]征途【dp】

【题目链接】
  http://www.lydsy.com/JudgeOnline/problem.php?id=4518
【题解】
  斜率优化dp。
  首先不难想到一个O(n3)的暴力,由于平均值是固定的,记f[i][j]表示到了第i站,停了j次的方差最小值,f[i][j]=min(f[k][j1]+(s[i]s[k1]x¯)2) ik
  将这东西展开,就能得到k1k2优的条件:(k1>k2)

(f[k1][j1]+s[k1]s[k1]+2x¯f[k1]f[k2][j1]s[k2]s[k2]2x¯f[k2])/(2(s[k1]s[k2]mm))<s[i]

  时,k1k2优。

/* --------------
    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;
}
posted @ 2018-03-16 20:25  Vanisher  阅读(94)  评论(0编辑  收藏  举报