POJ - 3666 Making the Grade 二维dp

Making the Grade
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 7096   Accepted: 3282

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 B 1| + | A 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

题意是改变原来的序列,使得新序列变为非递增(ai<=aj,i>j)或非递减序列(ai>=aj,i>j)

其中问最小的变化量是多少  

对于每一个数,要么改成它前面的数,要么改成它后面的数,(可以写几个看一下),所以正确的改法最后所有数一定还是之前的那些数

这样就可以维护二维dp

维护非递减时,dp【i】【j】表示前i个形成最大值为j的非递减序列所需的最小改变量,其中j很明显只能是原序列里的数

第二个维度直接用数表示空间会不够用,所以可以离散化一下,j对应原序列a里的某一个数 c【j】=a【x】;

这样dp【i】【j】表示前i个形成最大值为c【j】的非递减序列所需的最小改变量

dp【i】【j】=min(dp【i-1】【k】)+abs(a【i】-c【j】)(其中c【k】<=c【j】)

这样是On^3的复杂度,很好想优化,就是事先排一下序,从小到大枚举c【j】,这样On^2的复杂度,就可以解决问题了

求非递增同理


#include
#include
#include
using namespace std;
long long int dp[2][2005][2005];
int cmp1(long long u,long long v)
{
	return u>v;
}
int cmp2(long long u,long long v)
{
	return u



你可能感兴趣的:(-----,D,P,------,poj)