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
|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.
Sample Input
7
1
3
2
4
5
3
9
Sample Output
3
Source
USACO 2008 February Gold
如果要让序列变成单调不上升或者单调不下降,对于某个位置而言,一定改成和他前一个一样,或者和他后一个一样,所以最后形成的序列的数都在原序列里出现过,考虑b数组保存排完序后的原数组值,
dp[i][j]表示第i个位置的值改成b数组中第j个数的值,且前i个有序(单调不上升或者单调不下降)
dp[i][j] = min (dp[i - 1][k])+ abs (a[i] - b[j])
最小的dp[i - 1][k]可以边循环边找,且k<=j
做两次,一次使得序列最后单调不上升,另一次使得序列最后单调不下降
/*************************************************************************
> File Name: poj3666.cpp
> Author: ALex
> Created Time: 2015年02月14日 星期六 13时48分09秒
************************************************************************/
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const double pi = acos(-1);
const int inf = 0x3f3f3f3f;
const double eps = 1e-15;
typedef long long LL;
typedef pair <int, int> PLL;
int dp[2010][2010];
int a[2010];
int b[2010];
int cmp (int a, int b)
{
return a > b;
}
void DP (int n)
{
memset (dp, inf, sizeof(dp));
for (int i = 1; i <= n; ++i)
{
dp[1][i] = abs (b[i] - a[1]);
}
for (int i = 2; i <= n; ++i)
{
int mins = inf;
for (int j = 1; j <= n; ++j)
{
mins = min (mins, dp[i - 1][j]);
dp[i][j] = min (dp[i][j], mins + abs (a[i] - b[j]));
}
}
}
int main ()
{
int n;
while (~scanf("%d", &n))
{
for (int i = 1; i <= n; ++i)
{
scanf("%d", &a[i]);
b[i] = a[i];
}
sort (b + 1, b + 1 + n);
DP(n);
int ans = inf;
for (int i = 1; i <= n; ++i)
{
ans = min (ans, dp[n][i]);
}
sort (b + 1, b + 1 + n, cmp);
DP (n);
for (int i = 1; i <= n; ++i)
{
ans = min (ans, dp[n][i]);
}
printf("%d\n", ans);
}
return 0;
}