BZOJ-4518 征途

Description

Pine开始了从S地到T地的征途。
从S地到T地的路可以划分成n段,相邻两段路的分界点设有休息站。
Pine计划用m天到达T地。除第m天外,每一天晚上Pine都必须在休息站过夜。所以,一段路必须在同一天中走完。
Pine希望每一天走的路长度尽可能相近,所以他希望每一天走的路的长度的方差尽可能小。
帮助Pine求出最小方差是多少。
设方差是v,可以证明,v×m^2是一个整数。为了避免精度误差,输出结果时输出v×m^2。

Input

第一行两个数 n、m。
第二行 n 个数,表示 n 段路的长度

Output

 一个数,最小方差乘以 m^2 后的值

Sample Input

5 2
1 2 5 8 6

Sample Output

36

HINT

1≤n≤3000,保证从 S 到 T 的总路程不超过 30000

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
int I(){int x=0,f=1;char c=getchar();
    for(;c<'0'||c>'9';c=getchar())if(c=='-')f=-1;
    for(;'0'<=c&&c<='9';c=getchar())x=(x<<3)+(x<<1)+(c^48);return x*f;}
#define M 3010
ll f[M],s[M],tmp[M],q[M],l,r,a[M];
#define g(x) (tmp[x] + s[x]*s[x])
inline double T(ll p,ll q){return (double)(g(p)-g(q))/(double)(s[p]-s[q]);}
int main(){ll n,k;n=I();k=I();ll sum=0;
    for(ll i=1;i<=n;++i)a[i]=I(),sum+=a[i],s[i]=s[i-1]+a[i],tmp[i]=s[i]*s[i];
    for(ll j=2;j<=k;++j){l=0;r=-1;q[++r]=j-1;
        for(ll i=j;i<=n;++i){
            while(l<r&&T(q[l],q[l+1])<2.0*s[i])++l;
            f[i]=tmp[q[l]]+(s[i]-s[q[l]])*(s[i]-s[q[l]]);
            while(l<r&&T(q[r-1],q[r])>T(q[r],i))--r;q[++r]=i;
        }memcpy(tmp,f,sizeof f);}printf("%lld
",f[n]*k-sum*sum);
    return 0;}
原文地址:https://www.cnblogs.com/muzu/p/7966482.html