题目:洛谷P3195、BZOJ1010。
题目大意:
$$dp[i]=minlimits _{j<i}{dp[j]+(i-j-1+sumlimits _{k=j+1} ^i c_k -L)^2}$$
求(dp[n])
解题思路:
记(a_i=sumlimits _{j=1}^i c_j ),
则(dp[i]=minlimits _{j<i}{dp[j]+(i-j-1+a_i -a_j-L)^2})
令(b_i=a_i+1),(d_i=b_i-L-1),则(dp[i]=minlimits _{j<i}{dp[j]+(d_i-b_j)^2})
若状态(j)比(k)优秀,则(dp[j]+(d_i-b_j)^2 <dp[k]+(d_i-b_k)^2)
化简得(dp[j]+b_j ^2 -dp[k]-b_k^2 <(2b_j -2b_k)d_i)
令(x_i=2b_i),(y_i=dp[i]+b_i),则( y_j-y_k<(x_j-x_k)d_i )
考虑(j<k<l),有(x_j<x_k<x_l)
若(k)有用,则存在(d_i)使得(y_k-y_lleqslant (x_k-x_l)d_i ,y_k-y_j<(x_k-x_j)d_i)
于是(frac{y_k-y_j}{x_k-x_j}<d_ileqslant frac{y_l-y_k}{x_l-x_k})
然后单调队列维护斜率即可。
(以上抄自lyx_cjz)
C++ Code:
//f[i]=min{f[j]+(i-j-1+s[i]-s[j-1]-L)^2} //b[i]=s[i]+i,d[i]=b[i]-L-1 #include<bits/stdc++.h> #define LoveLive long long #define N 50005 int n,l; LoveLive f[N],s[N]; int q[N],c[N]; inline LoveLive b(const int i){return s[i]+i;} inline LoveLive d(const int i){return s[i]+i-l-1;} inline LoveLive sqr(const LoveLive t){return t*t;} inline LoveLive x(const int i){return b(i)<<1;} inline LoveLive y(const int i){return f[i]+sqr(b(i));} inline double slope(const int a,const int b){ return 1.*(y(a)-y(b))/(x(a)-x(b)); } int main(){ scanf("%d%d",&n,&l); s[0]=0; for(int i=1;i<=n;++i){ scanf("%d",&c[i]); s[i]=s[i-1]+c[i]; } q[0]=0;f[0]=0; int l=0,r=0; for(int i=1;i<=n;++i){ while(l<r&&slope(q[l],q[l+1])<=d(i))++l; f[i]=f[q[l]]+sqr(b(q[l])-d(i)); while(l<r&&slope(q[r-1],q[r])>=slope(q[r],i))--r; q[++r]=i; } printf("%lld ",f[n]); return 0; }