# 题目：

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

|A1 - B1| + |A2 - B2| + … + |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.

7
1
3
2
4
5
3
9

3

# 分析：

1.这道题dp还是好理解的，即离散化过后每次枚举当第i个山峰到达某山峰高度，dp[i][j]表示把前i个数变成单调增且第i个数变成原来第j大的数的最小代价。
2、把给定的山峰高度排好序，就成为其离散的递增或递减的高度。
3、对第一点进行与排好序的最小值的点进行比较，求得dp[0][j]要升到第j的高度时所要的花费
4、对第二点及以后的每一点进行更新。dp[i][j]第i+1点到高度j时的前i+1个总的花费

5、找到更后最后一个点到任意高度的最小值便为答案

# AC代码：

#include<string.h>
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int M=2e3+10;
int n,k;
int a[M],b[M],c[M];
int dp[M][M],e[M][M];///用数组下标进行离散化，表示某位置最小的花费
bool cmp(int x,int y)
{
return x>y;
}
int main()
{
cin>>n;
for (int i=0; i<n; i++)
cin>>a[i],b[i]=c[i]=a[i];
sort(b,b+n);
for (int i=0; i<n; i++)
dp[0][i]=abs(b[i]-a[0]);
for(int i=1; i<n; i++)//枚举第几座山峰
{
k=dp[i-1][0];
for (int j=0; j<n; j++)///枚举山峰到达离散化后某高度
{
k=min(k,dp[i-1][j]);
dp[i][j]=k+abs(b[j]-a[i]);
}
}
sort(c,c+n,cmp);
for (int i=0; i<n; i++)
e[0][i]=abs(c[i]-a[0]);
for(int i=1; i<n; i++)
{
k=e[i-1][0];
for (int j=0; j<n; j++)
{
k=min(k,e[i-1][j]);
e[i][j]=k+abs(c[j]-a[i]);
}
}
int ans=dp[n-1][0];
for (int i=0; i<n; i++)
ans=min(ans,min(dp[n-1][i],e[n-1][i]));
cout<<ans<<endl;
return 0;
}


• 点赞 1
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

zeng_jun_yv

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-24
02-12 2497

06-25 179
02-05 557
08-19 156
06-24 164
03-13 1076
05-23 91