Making the Grade
POJ - 3666A 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.
* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer elevation: Ai
* 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.
7 1 3 2 4 5 3 9Sample Output
3
题意:
给定一个序列,以最小代价将其变成单调不增或单调不减序列,这里的代价看题目公式。
1.
对前i个序列,构成的最优解其实就是与两个参数有关。一个是这个序列处理后的最大值mx,和这个序列处理的代价值cost。
显然最大值mx最小最好(这样第i+1个值可以不花代价直接接在其后面的可能性更大),cost最小也最好(题意要求),但是两者往往是鱼和熊掌。
用dp[i][j]表示:前i个数构成的序列,这个序列最大值为j,dp[i][j]的值代表相应的cost。
所以状态转移方程如下:
dp[i][j]=abs(j-w[i])+min(dp[i-1][k]);(k<=j)
这个表格是根据转移方程写出来的dp数组。
再仔细看一下转移方程:dp[i][j]=abs(j-w[i])+min(dp[i-1][k]);(k<=j)
右边没填充的是因为填充的数字肯定比前面的数字大,无用,因为在求min( dp[i-1][k] )时,是求最小值,既然更大,则最小值时无需考虑。
又从表格中可以看出:dp[i][j]=abs(j-w[i])+min(dp[i-1][k]);(k<=j)这里的k无需从1遍历到j。
只要在对j进行for循环的时候不断更新一个dp[i-1][j]的最小值mn=min(mn,dp[i-1][j]),
然后对dp[i][j]=abs(j-w[i])+mn即可;
这样改进之后即可从本来的时候时间复杂度O(NMM)改进为O(NM);
但是,这里的m是A[i]的最大值,显然TLE,并且dp数组也存不了。
所以必须用离散化思想改进,因为N=2000。远小于A[i]的最大值。
离散化:将序列排序一下,然后用位置编号代表高度,这样时间复杂度变成O(N^2),计算的时候还是用原高度.
code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
ll dp[2005][2005],a[2005],b[2005];
ll Abs(ll x){
if(x < 0) return -x;
else return x;
}
int n;
int main(){
while(~scanf("%d",&n)){
for(int i = 1; i <= n; i++){
scanf("%lld",&a[i]);
b[i] = a[i];
}
sort(b+1,b+1+n);
memset(dp,0,sizeof(dp));
for(int i = 1; i <= n; i++){//枚举每个数
ll minx = dp[i-1][1];
for(int j = 1; j <= n; j++){//枚举高度
minx = min(minx,dp[i-1][j]);
dp[i][j] = Abs(a[i]-b[j]) + minx;
}
}
ll ans = dp[n][1];
for(int i = 1; i <= n; i++){
ans = min(ans,dp[n][i]);
}
printf("%lld\n",ans);
}
return 0;
}