Making the Grade POJ - 3666

时间:2021-06-24 06:46:55

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

题解:
  这个题目我们先考虑暴力,dp[i][j]表示dp到i这一位,最后一个数是j的最小花费,那么状态数是n*(l~r),显然是不行的。
  考虑一个小优化,因为只有数j在序列中出现过才会有用,所以第二维可以改为第j大的数,这样子状态数就是n^2级别的了,转移是(上升)dp[i][j]=min(dp[i-1][1~j])+abs(hi[i]-hi[j)。
  把这个式子列出来就知道怎么优化转移了,计D[i][j]=min(dp[i][1~j]),那么转移就是D[i][j]=min*+(D[i][j-1],dp[i][j]),转移就变成O(n)的了。
代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#define MAXN 2020
#define inf 0x3f3f3f3f3f
#define ll long long
using namespace std;
ll dp[MAXN][MAXN],last[MAXN],hi[MAXN],rak[MAXN],D[MAXN][MAXN],ans=inf;
int n; ll abss(ll x){
if(x<) return -x;
return x;
} int main()
{
scanf("%d",&n);
for(int i=;i<=n;i++) scanf("%lld",&hi[i]),rak[i]=hi[i];
sort(rak+,rak+n+);
memset(D,inf,sizeof(D));
memset(dp,inf,sizeof(dp));
for(int i=;i<=n;i++) dp[][i]=;
for(int i=;i<=n;i++)
for(int j=;j<=n;j++){
if(i==) dp[i][j]=abss(hi[i]-rak[j]);
else dp[i][j]=D[i-][j]+abss(hi[i]-rak[j]);
D[i][j]=min(D[i][j-],dp[i][j]);
}
for(int i=;i<=n;i++) ans=min(ans,dp[n][i]);
memset(dp,inf,sizeof(dp));
memset(D,inf,sizeof(D));
for(int i=;i<=n;i++) dp[][i]=;
for(int i=;i<=n;i++)
for(int j=n;j>=;j--){
if(i==) dp[i][j]=abss(hi[i]-rak[j]);
else dp[i][j]=D[i-][j]+abss(hi[i]-rak[j]);
D[i][j]=min(D[i][j+],dp[i][j]);
}
for(int i=;i<=n;i++) ans=min(ans,dp[n][i]);
printf("%lld\n",ans);
return ;
}