POJ3666 Making the Grade 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 A_1, . . . , A_N (1 <= N <= 2,000) describing the elevation (0 <= A_i <= 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 B_1, . . . , B_N 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| + ... + |A_N - B_N|

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: A_i

输出

* 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
9

样例输出

3

提示

OUTPUT DETAILS:

By changing the first 3 to 2 and the second 3 to 5 for a total cost of |2-3|+|5-3| = 3 we get the nondecreasing sequence 1,2,2,4,5,5,9.

题意:给你一个序列,让你搞成不递减序列或者不递增序列,设原数组为a,改后的数组为c,每改一个数花费的代价为abs(a[i]-c[j])求改成c数组花费的最小代价    本题数据有问题,只要搞成不递减数组就ok

思路:显然改成的c数组出现的所有数一定在a数组中出现过,那么可以先将a数组copy给b数组,然后将b数组排序

DP[i][j]表示a数组前i个数改成以b数组第j个数为结尾的不递减数列的最小花费

那么 DP[i][j]这么转移过来呢

因为是不递减,所以改后的a数组前i-1个数的最后一个数一定是b数组前j个数中的一个,那么把a[i]改成b[j]花费的钱为

DP[i][j]=min(dp[i-1][k])+abs(a[i]-b[j])其中k<=j;这里因为决策集合是和j相关的,所以并不用每次去找min(dp[i-1][k])只要用一变量每次这样更新 v=min(v,dp[i-1][j])这个v==min(dp[i-1][k])其中k<=j;

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstdlib>
#include<deque>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int>P;
const int len=2e3+5;
const double pi=acos(-1.0);
const ll mod=1e9+7; 
ll dp[len][len];
int a[len],b[len];
int main()
{	
	int n; 
	cin>>n;
	for(int i=1;i<=n;++i)cin>>a[i],b[i]=a[i];
	sort(b+1,b+1+n);
	ll ans=1e18;
	for(int i=1;i<=n;++i)
	{
		ll v=1e18;
		for(int j=1;j<=n;++j)
		{
			v=min(v,dp[i-1][j]);
			dp[i][j]=v+fabs(a[i]-b[j]);
			if(i==n)ans=min(ans,dp[i][j]);
		}
	}
	cout<<ans<<endl;
}


猜你喜欢

转载自blog.csdn.net/hutwuguangrong/article/details/86584298