4518: [Sdoi2016]征途
Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 1657 Solved: 915
[Submit][Status][Discuss]
Description
Input
Output
一个数,最小方差乘以 m^2 后的值
Sample Input
1 2 5 8 6
Sample Output
HINT
1≤n≤3000,保证从 S 到 T 的总路程不超过 30000
Source
推公式
设s1[i]=1+2+...+i x=s1[n]/m
方差v=((x1-x)^2+(x2-x)^2+...+(xm-x)^2)/m
直接拆开所有平方
v*m^2=m*(x1^2+x2^2+...+xm^2)-2*(x1+x2+...+xm)^2-(m^2)*(x^2)
(m^2)*(x^2)=s1[n]^2 x1+x2+...+xm=s1[n]^2
ans=v*m^2=m*(x1^2+x2^2+...+xm^2)-s1[n]^2
其实化简之后发现 需要知道的是每一天的路程
那么考虑dp
dp[cur][i]=dp[cur-1][j]+(sum[i]-sum[j])^2
ans=dp[m][n]*m-sum[n]^2
斜率优化
dp[j]+(sum[i]-sum[j]-x)^2<=dp[k]+(sum[i]-sum[k]-x)^2
dp[j]-2*(sum[i]-x)*sum[j]+sum[j]^2
<=dp[k]-2*(sum[i]-x)*sum[k]+sum[k]^2
2*sum[i]>=
(dp[j]-dp[k]+sum[j]^2-sum[k]^2)/(sum[j]-sum[k])
1 #include<cstdio> 2 const int MAXN=3e3+10; 3 int n,m; 4 int s[MAXN]; 5 int q[MAXN],l,r; 6 long long f[MAXN][MAXN]; 7 double count_y(int k,int j){return f[k][j-1]+s[k]*s[k];} 8 double count(int t,int k,int j){return (count_y(t,j)-count_y(k,j))/(s[t]-s[k]);} 9 int main() 10 { 11 scanf("%d%d",&n,&m); 12 for(int i=1;i<=n;++i) 13 { 14 int x; 15 scanf("%d",&x); 16 s[i]=s[i-1]+x; 17 } 18 for(int i=1;i<=n;++i)f[i][1]=s[i]*s[i]; 19 for(int j=2;j<=m;++j) 20 { 21 l=1,r=1; 22 for(int i=1;i<=n;++i) 23 { 24 while(l<r&&count(q[l],q[l+1],j)<2*s[i])++l; 25 int temp=q[l]; 26 f[i][j]=f[temp][j-1]+(s[i]-s[temp])*(s[i]-s[temp]); 27 while(l<r&&count(q[r],i,j)<count(q[r-1],q[r],j))--r; 28 q[++r]=i; 29 } 30 } 31 printf("%lld\n",f[n][m]*m-(long long)s[n]*s[n]); 32 return 0; 33 }