Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7185 | Accepted: 3325 |
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 1 - B 1| + | A 2 - 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
题意:有人想修一条尽量平缓的路,要么单调递增,要么单调递减,路的每一段海拔是A[i],若修理后是B[i],花费 | A[i] – B[i] | ,求最小花费
解题思路:最后不管怎么改变,最终的所有数都是原来的某个数,因为A[i]较大,所以可以对a[i]进行离散化,dp[i][j]表示第i个数变为原序列第j大的最小费用
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <cmath>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>
using namespace std;
#define LL long long
const LL INF = 0x3f3f3f3f3f3f3f3f;
int n, m;
int a[2005], b[2005];
LL dp[2005][2005];
int main()
{
while (~scanf("%d", &n))
{
for (int i = 1; i <= n; i++) scanf("%d", &a[i]), b[i] = a[i];
sort(b + 1, b + n + 1);
int m = unique(b + 1, b + 1 + n) - b;
for (int i = 1; i <= m - 1; i++) dp[1][i] = abs(b[i] - a[1]);
for (int i = 2; i <= n; i++)
{
LL temp = INF;
for (int j = 1; j <= m - 1; j++)
{
temp = min(temp, dp[i - 1][j]);
dp[i][j] = abs(b[j] - a[i]);
dp[i][j] += temp;
}
}
LL ans = INF;
for (int i = 1; i <= m - 1; i++) ans = min(ans, dp[n][i]);
for (int i = 1; i <= m - 1; i++) dp[1][i] = abs(b[i] - a[1]);
for (int i = 2; i <= n; i++)
{
LL temp = INF;
for (int j = m-1; j >= 1; j--)
{
temp = min(temp, dp[i - 1][j]);
dp[i][j] = abs(b[j] - a[i]);
dp[i][j] += temp;
}
}
for (int i = 1; i <= m - 1; i++) ans = min(ans, dp[n][i]);
printf("%lld\n", ans);
}
return 0;
}