题目描述

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 describing the elevation () 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
 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.

输入描述:

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

输出描述:

* 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.

示例1

输入
7
1
3
2
4
5
3
9
输出
3
说明
By changing the first 3 to 2 and the second 3 to 5 for a total cost of |2-3|+|5-3| = 3 we get the nondecreasing sequence 1,2,2,4,5,5,9.

解答

中文大意
农夫约翰想修一条尽量平缓(海拔单调增或单调减(非严格,下同))的路,路的每一段海拔是,修理后是,花费,求最小花费。
具体思路
该题目有两种情况:一种是变成单调增序列,一种是变成单调减序列。因此打算分两种情况进行计算:
以单调增为例。我们可以很容易证明得最终得出的序列的每一个元素都是原来序列中的某一个元素。即原序列得到最终结果,其中
用反证法可以求得:若存在使得 ,但或者可能更加接近,进一步想想看就可以证明正确性了。
所以可以列出dp状态转移方程:
个数变成单调且最后一个数是,此时的最小成本。

这对于单调减序列,亦然。
为了节省内存空间,我们不妨利用滚动数组求解。
参考代码
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>

using namespace std;
static const int N_MAX = 2001;
static const int INF = 1<<21;

int dp[2][N_MAX];
int A[N_MAX];
int B[N_MAX];

int N;
int solveUp()
{
    //init
    sort(B+1,B+N+1);
    for(int j=1;j<=N;j++)
    {
        dp[1][j] = abs(A[1] - B[j]);
    }

    for(int i=2;i<=N;i++)
    {
        int preMinCost = dp[(i-1)%2][1];
        for(int j=1;j<=N;j++)
        {
            preMinCost = min(preMinCost,dp[(i-1)%2][j]);
            dp[i%2][j] = preMinCost + abs(A[i]-B[j]);
        }
    }

    return *min_element(dp[N%2]+1,dp[N%2]+N+1);
}

int solveDown()
{
    //init
    sort(B+1,B+N+1);
    for(int j=1;j<=N;j++)
    {
        dp[1][j] = abs(A[1] - B[N+1-j]);
    }

    for(int i=2;i<=N;i++)
    {
        int preMinCost = dp[(i-1)%2][1];
        for(int j=1;j<=N;j++)
        {
            preMinCost = min(preMinCost,dp[(i-1)%2][j]);
            dp[i%2][j] = preMinCost + abs(A[i]-B[N+1-j]);
        }
    }

    return *min_element(dp[N%2]+1,dp[N%2]+N+1);
}
int main()
{
    cin>>N;
    for(int i=1;i<=N;i++)
    {
        cin >> A[i];
        B[i] = A[i];
    }
    cout<<min(solveDown(),solveUp())<<endl;
}


来源:Jeza