题目链接:POJ - 3186
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 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.
Given the values v(i) of each of the treats lined up in order of the index i in their box, what is the greatest value FJ can receive for them if he orders their sale optimally?
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)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.
题意:一个序列可以从左边取也可以从右边取 第i次取的可以获得 i*v(i) 的贡献 (v(i)是第i次取得的权值) 求最大的贡献
第一种方法 由外向内推:
设 表示左边取完i个右边取完j个 的最大值 我们考虑一些如何转移
边界条件
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 2003;
typedef long long ll;
ll dp[N][N],a[N];
int main(){
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i++) scanf("%lld",&a[i]);
dp[0][0]=0;
for(int i = 1; i <= n; i++)
dp[i][0]=dp[i-1][0]+1ll*i*a[i],dp[0][i]=dp[0][i-1]+1ll*i*a[n-i+1];
for(int i = 1; i <= n; i++){
for(int j = 1; i+j <= n; j++)
dp[i][j]=max(dp[i-1][j]+a[i]*1ll*(i+j),dp[i][j-1]+a[n-j+1]*1ll*(i+j));
}
ll ans = 0;
for(int i = 0; i <= n; i++)
ans=max(dp[i][n-i],ans);
printf("%lld\n",ans);
return 0;
}
第二种方法 由内向外推:
这个就是区间dp了 但是没有三重 只有两层 简单递推即可
表示区间 l 到 r 可以取到的最大值
区间dp有一个精髓的地方在于是由小区间开始 去推大的区间 初始状态就是一个元区间(长度为1的区间)
我们考虑出状态的值是多少 显然 因为一个区间肯定是最后被取到的 所以 :
考虑转移:
稍微有点丑 大家凑合着看 也就是一个区间要么是由 l+1 到 r 这个区间加上 a[ l ] 的贡献而来 要么是由 l 到 r-1 这个区间加上a[ r ] 而来 我们取最大值即可
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
int n;
ll dp[2003][2003],a[2003];
int main(){
scanf("%d",&n);
for(int i = 1; i <= n; i++) scanf("%lld",&a[i]);
for(int i = 1; i <= n; i++) dp[i][i]=1ll*n*a[i];
for(int i = 2; i <= n; i++){
for(int l = 1; l <= n-i+1; l++){
int r = l+i-1;
dp[l][r]=max(dp[l+1][r]+1ll*(n-r+l)*a[l],dp[l][r-1]+1ll*(n-r+l)*a[r]);
}
}
printf("%lld\n",dp[1][n]);
return 0;
}