BZOJ-4518 征途
阿新 • • 發佈:2017-12-03
tchar esc col fin div nbsp ron tput clu
1 2 5 8 6
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 21 2 5 8 6
Sample Output
36HINT
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\n",f[n]*k-sum*sum); return 0;}
BZOJ-4518 征途