POJ - 3666 Making the Grade(dp+离散化)

时间:2022-09-30 06:50:26

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

9

Sample Output

题目链接:http://poj.org/problem?id=3666

推荐题解链接:http://www.hankcs.com/program/cpp/poj-3666-making-the-grade.html

**********************************************

题意:给定一个正整数序列a[1...n],要求你改变每一个数变成b[1...n],使得改变后的序列非严格单调,改变的代价为abs(a[1]-b[1])+...+abs(a[n]-b[n]),求代价最小值。

分析:dp+离散化。

显然b[i]必定为a[1...n]中的某个值,且由于a过大,所以离散化。我们将每个数离散化 然后排序。设dp[i][j]为第i个数改变为b[j]时代价最小值,

则dp[i][j]=min(dp[i-1][k])+abs(a[i]-b[j]),然后 b数组表示的就是 离散过的 那些数据。

AC代码:

 #include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
#include<time.h>
#include<stack>
using namespace std;
#define N 12000
#define INF 0x3f3f3f3f int b[N],a[N],dp[N]; int main()
{
int n,i,j; while(scanf("%d", &n) != EOF)
{
memset(dp,,sizeof(dp));
memset(a,,sizeof(a));
memset(b,,sizeof(b)); for(i=;i<n;i++)
{
scanf("%d", &a[i]);
b[i]=a[i];
} sort(b,b+n); for(i=;i<n;i++)
dp[i]=abs(a[]-b[i]); for(i=;i<n;i++)
{
int mi=INF;
for(j=;j<n;j++)
{
mi=min(mi,dp[j]);
dp[j]=mi+abs(a[i]-b[j]);
}
} int minn=INF;
for(i=;i<n;i++)
minn=min(dp[i],minn); printf("%d\n",minn);
}
return ;
}