A-Making the Grade(POJ 3666)

时间:2021-12-23 09:34:09
Making the Grade
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 4656   Accepted: 2206

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

Source

经典dp

dp[i][j]表示第i个数变成第j小的数的最小消耗。

dp[i][j] = dmin[i - 1][j] + abs(o[i] - d[j]) (ps : dmin[i - 1][j] 表示前i - 1个数并且第i - 1个数小于等于j的最小消耗, abs(o[i] - d[j]) 表示第i个数变成j的消耗);

数据较水,只保证是上升序列即可。

#include <cstdio>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
#define ll long long
#define _cle(m, a) memset(m, a, sizeof(m))
#define repu(i, a, b) for(int i = a; i < b; i++)
#define MAXN 2005
ll dp[MAXN][MAXN];
ll dmin[MAXN][MAXN];
ll d[MAXN], o[MAXN];
int main()
{
int n;
scanf("%d", &n);
repu(i, , n + ) { scanf("%I64d", &d[i]); o[i] = d[i]; }
sort(d + , d + n + );
int l = ;
repu(i, , n + ) if(d[i] != d[l]) d[++l] = d[i]; repu(i, , l + ) {
dp[][i] = (ll)abs((int)o[] - (int)d[i]);
if(i == ) dmin[][i] = dp[][i];
else dmin[][i] = min(dp[][i], dmin[][i - ]);
}
ll t = ;
repu(i, , n + ) {
dp[i][] = dp[i - ][] + (ll)abs((int)o[i] - (int)d[]);
dmin[i][] = dp[i][];
repu(j, , l + ) {
dp[i][j] = dmin[i - ][j] + (ll)abs((int)o[i] - (int)d[j]);
dmin[i][j] = min(dp[i][j], dmin[i][j - ]);
}
}
printf("%I64d\n", dmin[n][l]);
return ;
}