Making the Grade POJ - 3666 (dp 离散化 变成 非严格单调递增 或递减)

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 B 1| + | A 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

题意:农夫约翰想修一条尽量平缓的路,路的每一段海拔是A_i,修理后是B_i,花费|A_i – B_i|,求最小花费。

思路:

为什么叫离散化,我不懂,但状态转移方程应该懂; 
 dp[i][j] 表示前i个数组成的非严格递增的序列的最大值为b[j] 的 最小花费;
状态转移方程; 
dp[i][j] = abs(a[i] - b[j]) + min(dp[i-1][k]) (k<=j);

若是严格单调递增的话,(k<j),因为这题上给出的n个数有重复,所以要求严格单掉递增的话,(k<j)也不行; 
要是给出的n个数没有重复的可以尝试一下这个思路(k<j);
非严格单调递增是大于等于前面的数;

若一个序列本身不是非严格单调递增的话,要想经过最优改变变成非严格单调递增的话,那么其中变得值一定是n个数中的数的值; 

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define Max 2020
#define INF 0x3f3f3f3f
#include<stdlib.h>

int dp[Max][Max];
int a[Max],b[Max];
int n;
   
//为什么叫离散化,我不懂,但状态转移方程应该懂; 
//  dp[i][j] 表示前i个数组成的非严格递增的序列的最大值为b[j] 的 最小花费;
// 状态转移方程; 
//  dp[i][j] = abs(a[i] - b[j]) + min(dp[i-1][k]) (k<=j);
// 若是严格单调递增的话,(k<j),因为这题上给出的n个数有重复,所以要求严格单掉递增的话,(k<j)也不行; 
// 要是给出的n个数没有重复的可以尝试一下这个思路(k<j);
// 非严格单调递增是大于等于前面的数;
// 若一个序列本身不是非严格单调递增的话,要想经过最优改变变成非严格单调递增的话,那么其中变得值一定是n个数中的数的值; 
 
int main()
{
	int i,j;
	while(~scanf("%d",&n))
	{
		for(i = 1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			b[i] = a[i];
		}
		sort(b+1,b+(n+1));      // 把给出的n个数从小到大排序; 
		memset(dp[0],0,sizeof(dp[0]));
		for(i = 1;i<=n;i++)
		{
			int Mi = INF;
			for(j = 1;j<=n;j++)
			{
				Mi = min(Mi,dp[i-1][j]);   // 找出前i-1个数变成小于等于b[j]结尾的非严格单调递增的最小花费; 
				dp[i][j] = abs(a[i] - b[j]) + Mi;
			}
		}
		int Mi = INF;
		for(i = 1;i<=n;i++)
			Mi = min(Mi,dp[n][i]);
		printf("%d\n",Mi);
	}
	return 0;
}

阅读更多
个人分类: dp 动态规划
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Making the Grade POJ - 3666 (dp 离散化 变成 非严格单调递增 或递减)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭