Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7729 | Accepted: 3612 |
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
题意:给定一个数字序列,改变其中某些数字,让这个序列变成一个非递增或则会非递减的序列,求最小改变量。
解析:看了题解才明白这题解法。这个最小改变量可能是这个序列改变成非递增,也可能是非递减。由于数字非常大,且这些数字改变只能在这些数的最大值和最小值之间,所以可以把某个数字转化为第几小或者第几大,即离散化。以非递减为例,用dp[i][j]表示到将第i个数字改变成第j小的数字的最小改变量。dp[i][j] = min(dp[i-1][k])+abs(a[i]-b[j]),其中k<=j。
就是到第i个数字时,枚举这个数字变成从最小到最大数字的变化量。时间复杂度为O(n^2)
代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define INF 2000000000
#define N 2002
bool cmp(int x, int y){
return x > y;
}
int dp1[N][N], dp2[N][N], a[N], b[N], c[N];
int main(){
int n;
while(~scanf("%d", &n)){
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
b[i] = c[i] = a[i];
}
sort(b+1, b+n+1);
sort(c+1, c+n+1, cmp);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
dp1[i][j] = dp2[i][j] = INF;
for(int i = 1; i <= n; i++){
dp1[1][i] = abs(a[1] - b[i]);
dp2[1][i] = abs(a[1] - c[i]);
}
int ans = INF;
for(int i = 1; i <= n; i++){
int Min1 = INF, Min2 = INF;
for(int j = 1; j <= n; j++){
Min1 = min(Min1, dp1[i-1][j]);
Min2 = max(Min2, dp2[i-1][j]);
dp1[i][j] = min(dp1[i][j], Min1+abs(a[i]-b[j]));
dp2[i][j] = min(dp2[i][j], Min2+abs(a[i]-b[j]));
if(i == n){
ans = min(ans, dp1[i][j]);
ans = min(ans, dp2[i][j]);
}
}
}
printf("%d\n", ans);
}
return 0;
}