poj 3666 Making the Grade (离散化+动态规划)

来源:互联网 发布:阿里云对个人有什么用 编辑:程序博客网 时间:2024/06/05 19:08
Making the Grade
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 7794 Accepted: 3639

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

|AB1| + |AB2| + ... + |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

71324539

Sample Output

3

Source

USACO 2008 February Gold

[Submit]   [Go Back]   [Status]   [Discuss]

Home Page   Go Back  To top



看这个图吧。。

我们可以dp一下 i 是遍历到第几个数   j代表的是最大值

int tmp = dp【i-1】【k】(k<=j)

dp【i】【j】=abs(a[i]-j)+tmp

因为 j的取值范围是 1e9 而 n 的数据范围是2000

离散数据减少空间范围






#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define N 2002int a[N];int b[N];long long  dp[N][N];int main(){    int n;    while(~scanf("%d",&n))    {        for(int i=1;i<=n;i++)        {            scanf("%d",&a[i]);            b[i]=a[i];        }        sort(b+1,b+n+1);        for(int i=1;i<=n;i++)        {            long long tmp=dp[i-1][1];            for(int j=1;j<=n;j++)            {                tmp=min(tmp,dp[i-1][j]);                dp[i][j]=abs(a[i]-b[j])+tmp;            }        }        long long res=dp[n][1];        for(int i=1;i<=n;i++)        {            res=min(res,dp[n][i]);        }        printf("%lld\n",res);    }}


原创粉丝点击