POJ3666Making the Grade题解动态规划DP

Making the Grade
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 1977   Accepted: 912

Description

A straight dirt road connects two fields on FJ's farm, but it changes elevation more than FJ would like. His cows do not mind climbing up or down a single slope, but they are not fond of an alternating succession of hills and valleys. FJ would like to add and remove dirt from the road so that it becomes one monotonic slope (either sloping up or down).

You are given N integers A1, ... , AN (1 ≤ N ≤ 2,000) describing the elevation (0 ≤ Ai ≤ 1,000,000,000) at each of N equally-spaced positions along the road, starting at the first field and ending at the other. FJ would like to adjust these elevations to a new sequence B1, . ... , BN that is either nonincreasing or nondecreasing. Since it costs the same amount of money to add or remove dirt at any position along the road, the total cost of modifying the road is

| A 1 - B 1| + | A 2 - B 2| + ... + | AN - BN |

Please compute the minimum cost of grading his road so it becomes a continuous slope. FJ happily informs you that signed 32-bit integers can certainly be used to compute the answer.

Input

* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer elevation: Ai

Output

* Line 1: A single integer that is the minimum cost for FJ to grade his dirt road so it becomes nonincreasing or nondecreasing in elevation.

Sample Input

7
1
3
2
4
5
3
9

Sample Output

3

Source

USACO 2008 February Gold
因为求的是不增、不降序列,所以序列中的高度一定是出现过的高度
本题数据弱,只需求不降序列
高度值很大需要离散化
按h排序,记录原来的下标
状态:
d[i][j]表示第i根柱子高度为h[a[j].d]时最优值
状态转移方程:
d[i][j]=min{d[i-1][k]+abs(h[i]-h[a[k].d])|1<=k<j}
边界:
d[1][j]=abs(h[1]-h[a[j].d] )
代码:
#include<cstdio> #include<algorithm> #define N 2005 using namespace std; int d[2][N],n; struct node {int d,h; bool operator<(node t)const {return h<t.h;} }a[N]; int main() { scanf("%d",&n); int i,j,t,ans=-1u>>1,h[N]; for(i=1;i<=n;i++) { scanf("%d",h+i); a[i].h=h[i]; a[i].d=i; } sort(a+1,a+n+1); for(j=1;j<=n;j++) d[1][j]=abs(h[1]-h[a[j].d]); for(i=2;i<=n;i++) { t=d[(i+1)&1][1]; for(j=1;j<=n;j++) { t=min(t,d[(i+1)&1][j]); d[i&1][j]=t+abs(h[i]-h[a[j].d]); } } for(j=1;j<=n;j++) ans=min(ans,d[(i+1)&1][j]); printf("%d/n",ans); }

你可能感兴趣的:(POJ3666Making the Grade题解动态规划DP)