您的位置:首页 > 其它

POJ 3186 Treats for the Cows

2017-01-23 12:49 246 查看
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.

题意:简单说就是一个双向队列,每次可以从两端的一个端点处选择一只牛出售,获得的钱是vi*权值,权值就是第一头牛*1,第二头牛*2.......

思路:一开始想了个贪心,交上去是错的,虽然不知道反例是啥,但条件反射性的就认为是dp,区间dp不难想。

dp[i][j]为当前区间得到的最大值,那么当前状态就等于选择上面一只牛,或者底下的一只牛+上里面区间的值。

dp[i][j]=max(dp[i+1][j]+v[i]*权值,dp[i][j-1]+v[j]*权值)。

然后走一遍就可以啦,注意这里是dp[i+1]也就是i上一个状态i+1,所以n的循环要从n倒着来。

#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN=1e5+7;
int num[2005];
int dp[2005][2005];
int n,m;
int main()
{
int i,j;
scanf("%d",&n);
for(i=0; i<n; ++i)scanf("%d",&num[i]);
for(i=n-1; i>=0; --i)
for(j=i; j<n; ++j)
{
dp[i][j]=max(dp[i+1][j]+num[i]*(n-j+i),dp[i][j-1]+num[j]*(n-j+i));
}
printf("%d\n",dp[0][n-1]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 区间dp