ACM DP Making the Grade

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
7
1
3
2
4
5
3
9
Sample Output
 
 
 
 
 
 
题目大意,给一串数,每次只能从头部或者尾部取,每取一次,天数加一,每个数对应的价值就是本身乘以天数,问可以求得的价值最大值


代码如下

#include<stdio.h>
#include<algorithm>
using namespace std;
int v[2222],n,dp[2222][2222];//i到j的最大
int main()
{
    int i,j;
    while(scanf("%d",&n)!=EOF)
    {
        for(i=1;i<=n;i++)
            scanf("%d",&v[i]);
        for( i=n;i>=1;i--)  //一定要倒着来,是因为从前往后前面的会对后面的有重复影响,倒着来就不需要考虑;
            for(j=i;j<=n;j++)
                dp[i][j]=max(dp[i+1][j]+v[i]*(n+i-j),dp[i][j-1]+v[j]*(n+i-j));
        printf("%d\n",dp[1][n]);
    }
    return 0;
}
/*如果转移方程是从外向里,也就是说i用i-1表示,j用j+1表示,那么就会发现,dp[i][j]没有意义,中间是空的,所以我们用
里面到外面,观察到i由i+1得到,所以i为逆序。

猜你喜欢

转载自blog.csdn.net/stdio_xuege/article/details/80909083
今日推荐