Normal DP..
F[I][J] Represents the first I-pole, the minimum total cost of changing the height of the I pole to J. Set the original pole height to h[]
f[i][j]=min{
f[i-1][k]+c*|j-k|+ (J-h[i]) ^2, (K>=h[i-1],j>=h[i])
}
Directly on the words of Complexity is O (n*100*100) = =
You can use two arrays to save the K (two arrays with different values of J): One is K>=j, the other is K<=j, and the J value changes when the two auxiliary arrays are adjusted. See the code for details. That's the complexity of O (n*100).
1#include <cstdio>2#include <iostream>3#include <cstring>4 using namespacestd;5 Const intmaxn=100023;6 intf[2][101],gpre[101],gaft[101],H[MAXN];7 inti,j,k,n,m,ans,c,now,pre,tmp,mn,mx;8 intRaCharRx;9InlineintRead () {TenRx=getchar (); ra=0; One while(rx<'0'|| Rx>'9') rx=GetChar (); A while(rx>='0'&&rx<='9') ra*=Ten, ra+=rx- -, Rx=getchar ();returnRA; - } - intMain () { theN=read (); C=read (); now=1;p re=0; mn=2333333; - for(i=1; i<=n;i++) H[i]=read (), Mn=min (Mn,h[i]), mx=Max (mx,h[i]); - for(i=1; i<=n;i++){ - for(j=h[i];j<=mx;j++) f[now][j]= (J-h[i]) * (J-h[i]) +min (gpre[j],gaft[j]); + - for(tmp=j=h[i];j<=mx;j++)if(f[now][j]<f[now][tmp]+ (j-tmp) *c) tmp=j,gpre[j]=F[now][j]; + Elsegpre[j]=f[now][tmp]+ (j-tmp) *C; Amemset (Gpre, -,h[i]<<2); at for(tmp=j=mx;j>=h[i];j--)if(f[now][j]<f[now][tmp]+ (TMP-J) *c) tmp=j,gaft[j]=F[now][j]; - Elsegaft[j]=f[now][tmp]+ (TMP-J) *C; - for(j=h[i]-1; j;j--) gaft[j]=f[now][tmp]+ (tmp-j) *C; - swap (now,pre); - } - for(ans=f[pre][h[n]],i=h[n]+1; i<=mx;i++)if(F[pre][i]<ans) ans=F[pre][i]; inprintf"%d\n", ans); - return 0; to}
View Code
[bzoj1705] [Usaco2007 Nov] Telephone Wire Erection Telephone line