Making the Grade (线性+优化思维?)

来源:互联网 发布:淘宝引流有哪些软件 编辑:程序博客网 时间:2024/06/04 00:52

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
71324539
Sample Output
3


看了一天的博客,最后才想明白做法。

思路:可以这样设计DP, d[i][j]表示第i个数变成j的最优解, 这样它转移到d[i-1][k], 其中k<=j, 这是变成上升的, 代价是abs(a[i] - j)。 但是数太大了, 又因为每个数肯定会变成这些数中的一个数会最优, 所以我们不妨将n个数先离散化一下, 这样状态就表示成d[i][j]表示第i个数变成第j小的数, 转移到d[i-1][k],其中k<=j。 但是这样还是超时了, 因为是三重循环, 又发现,每次都是取前一层的当前最小值, 所以很容易将第3层优化掉。

思路大概就是这样。然后利用滚动数组就可以直接降维。感觉好难QAQ。

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<algorithm>using namespace std;const int MAXN = 2333;const int inf = 1e9;int n;int dp[MAXN],a[MAXN],b[MAXN],num[MAXN];int get_ans(int *a,int *num){    memset(dp,0,sizeof dp);    for(int i = 1 ; i <= n ; ++i)    {        int MIN = inf;        for(int j = 1 ; j <= n ; ++j)        {            MIN = min(MIN,dp[j]);            dp[j] = MIN + abs(a[i] - num[j]);        }    }    int ans = inf;    for(int i = 1 ; i <= n ; ++i)ans = min(ans,dp[i]);    return ans;}int main(){    scanf("%d",&n);    for(int i = 1 ; i <= n ;++i)    {        scanf("%d",&a[i]);        num[i] = a[i];        b[n-i+1] = a[i];    }    sort(num+1,num+1+n);    printf("%d\n",min(get_ans(a,num),get_ans(b,num)));    return 0;}

至于可能递增或递减这两种情况,我们把原序列倒着放一次,然后跑一次就可以了。是一样的。