kaungbin_DP S (POJ 3666) Making the Grade

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

AB1| + | AB2| + ... + | 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

显然这题的难点在于抉择第i点到底提升自己还是降低之前的
那么干脆就把所有可能考虑到 用dp[i][j]表示 第i点以j结尾的最小cost
但是题中给的数据量来看 这个数组实在太大 所以再加上离散化 那么就是O(n^2)的方法了

这题数据很水 只要非降序就能过

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;

int n, arry[2010], cast[2010];
int dp[2010][2010];

int main()
{
    ios::sync_with_stdio(false);
    while(cin >> n){
        for(int i = 0; i < n; ++i){
            cin >> arry[i];
        }
        memcpy(cast, arry, sizeof arry);
        sort(cast, cast + n);

        for(int i = 0; i < n; i++){
            dp[0][i] = abs(arry[0] - cast[i]);
        }

        for(int i = 1; i < n; i++){
            int mini = dp[i-1][0];
            for(int j = 0; j < n; j++){
                mini = min(dp[i-1][j], mini);
                dp[i][j] = abs(arry[i] - cast[j]) + mini;
            }
        }

        cout << *min_element(dp[n-1], dp[n-1] + n) << endl;
    }
    return 0;
}


原文地址:https://www.cnblogs.com/quasar/p/5308869.html