Description
FJ has purchased N (1 <= N <= 2000) yummy treats for the cows who get money for giving vast amounts of milk. FJ sells one treat per day and wants to maximize the money he receives over a given period time.
The treats are interesting for many reasons:
The first treat is sold on day 1 and has age a=1. Each subsequent day increases the age by 1.
The treats are interesting for many reasons:
- The treats are numbered 1..N and stored sequentially in single file in a long box that is open at both ends. On any day, FJ can retrieve one treat from either end of his stash of treats.
- Like fine wines and delicious cheeses, the treats improve with age and command greater prices.
- The treats are not uniform: some are better and have higher intrinsic value. Treat i has value v(i) (1 <= v(i) <= 1000).
- Cows pay more for treats that have aged longer: a cow will pay v(i)*a for a treat of age a.
The first treat is sold on day 1 and has age a=1. Each subsequent day increases the age by 1.
Input
Line 1: A single integer, N
Lines 2..N+1: Line i+1 contains the value of treat v(i)
Lines 2..N+1: Line i+1 contains the value of treat v(i)
Output
Line 1: The maximum revenue FJ can achieve by selling the treats
Sample Input
5 1 3 1 5 2
Sample Output
43
Hint
Explanation of the sample:
Five treats. On the first day FJ can sell either treat #1 (value 1) or treat #5 (value 2).
FJ sells the treats (values 1, 3, 1, 5, 2) in the following order of indices: 1, 5, 2, 3, 4, making 1x1 + 2x2 + 3x3 + 4x1 + 5x5 = 43.
Five treats. On the first day FJ can sell either treat #1 (value 1) or treat #5 (value 2).
FJ sells the treats (values 1, 3, 1, 5, 2) in the following order of indices: 1, 5, 2, 3, 4, making 1x1 + 2x2 + 3x3 + 4x1 + 5x5 = 43.
/* 题意:给你一个双向队列,每次可以从队首,或者从队尾取出元素,每次操作会获得相应的价值,第i个取出的元素a 得到的价值就是i*a,问你能取出的最大价值是多少 初步思路:先贪心搞一发试试 #改进:用一个数组b 存放着 逆序的数组 a,dp[i][j]表示,a数组取i 个,b数组取 j个时的最大值,得到状态转移方程: dp[i][j]=max(dp[i-1][j]+a[i]*(i+j),dp[i][j-1]+b[j]*(i+j)); 实际上就是 左边取 i 个,右边取 j 个的最大值 #错误:上面的初始化,没法搞,当i等于零或者j等于零的时候,问题就重新转化为题目要求的问题了,换一个思路,从里面向 外边扩,不从边上开始,从里往外,因为最终的顶点并不是确定的,dp[i][j]表示从i到j能得到的最大价值,得到状态 转移方程: dp[i][j]=max( dp[i+1][j]+a[i]*( n-j+i ), dp[i][j-1]+a[j]*( n-j+i ) ); #错误:得不到正确的结果 #注意:上面的想法没错,但是i是逆向循环的,因为正向循环的话,记录的状态都是接下来的状态,根本没有参考上一个状态, 进行判断结果 */ #include <iostream> #include <stdio.h> #include <string.h> using namespace std; int n; int l,r; int a[2005]; int dp[2005][2005]; void init(){ memset(dp,0,sizeof dp); memset(a,0,sizeof a); } int main(){ // freopen("in.txt","r",stdin); while(scanf("%d",&n)!=EOF){ init(); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); dp[i][i]=a[i]*n;//初始化每一个最后拿的话都是,a[i]*n } for(int i=n-1;i>=1;i--){ for(int j=i+1;j<=n;j++){ dp[i][j]=max( dp[i+1][j]+a[i]*( n-j+i ), dp[i][j-1]+a[j]*( n-j+i ) ); // cout<<"( "<<i<<" ,"<<j<<" ) "<<( n-j+i )<<endl; } } // for(int i=1;i<=n;i++){ // for(int j=1;j<=n;j++){ // cout<<dp[i][j]<<" "; // } // cout<<endl; // } printf("%d ",dp[1][n]); } return 0; }