POJ 3666 Making the Grade

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

|A1 - B1| + |A2 - B2| + ... + |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.

解题报告:
正解:DP
这题状态很好定义,因为是不严格递增递减,所以可以想象某个数的增加或减少后一定会是数列中的某个数,而不会是其他数,否则不会更优,所以我们就可以定义\(f[i][j][0/1]\)表示前i个数,最大值/最小值为数列中第j个数,0/1表示递增或递减的最小花费,转移很简单,方程参考代码及注释,注意第一维要滚掉

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#define RG register
#define il inline
#define iter iterator
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
const int N=2005;
const ll inf=2e15;
int a[N],b[N],m=0;ll f[2][N][2];
void work()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]),b[++m]=a[i];
	sort(b+1,b+m+1);
	int tot=unique(b+1,b+m+1)-b-1;
	for(int i=1;i<=n;i++)a[i]=lower_bound(b+1,b+tot+1,a[i])-b;
	for(int i=0;i<2;i++)
		for(int j=0;j<N;j++)
			f[i][j][0]=f[i][j][1]=inf;
	for(int i=1;i<=tot;i++){
		f[0][i][0]=a[1]<=i?0:abs(b[a[1]]-b[i]);
		f[0][i][1]=a[1]>=i?0:abs(b[i]-b[a[1]]);
	}
	bool t=1,tt=0;
	for(int i=1;i<n;i++){
		for(int j=1;j<=tot;j++){
			f[t][j][0]=Min(f[t][j][0],f[tt][j][0]+abs(b[a[i+1]]-b[j]));
			f[t][j][1]=Min(f[t][j][1],f[tt][j][1]+abs(b[j]-b[a[i+1]]));
			//Ai发生变化的转移
			if(j<=a[i+1])f[t][a[i+1]][0]=Min(f[t][a[i+1]][0],f[tt][j][0]);
			if(j>=a[i+1])f[t][a[i+1]][1]=Min(f[t][a[i+1]][1],f[tt][j][1]);
			//Ai不发生变化的转移
			f[tt][j][0]=f[tt][j][1]=inf;
			//滚动数组清空
		}
		for(int j=1;j<=tot;j++){
			if(j>1)f[t][j][0]=Min(f[t][j][0],f[t][j-1][0]);//这里不能忘记
			if(j<tot)f[t][j][1]=Min(f[t][j][1],f[t][j+1][1]);
		}
		t^=1;tt^=1;
	}
	ll ans=inf;
	for(int i=1;i<=tot;i++){
		ans=Min(ans,f[tt][i][0]);
		ans=Min(ans,f[tt][i][1]);
	}
	printf("%lld\n",ans);
}

int main()
{
	work();
	return 0;
}

posted @ 2017-09-09 19:39  PIPIBoss  阅读(138)  评论(0编辑  收藏  举报