Treats for the Cows
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5507 | Accepted: 2871 |
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
题意:
有一个长度为n的盒子里面装有不同价值的饼干,奶牛每次可以从左边或者右边拿饼干。ans = ∑ val[i] * (第几次拿的);求ans最大值;
题解:
很容易想到dp方程。设dp[i][j] 为 i-j 这一段的最大价值。。。dp[i][j] = max(dp[i+1][j] + val[i] * len, dp[i][j-1] + val[j] * len);其中len为第几次拿,len = n-(j-i);但是呢,转移方向需要考虑一下,注意到 i 是从右向左转移的,j 是从左向右转移的。那么dp的转移方向就应该是反向的。初始化所有的 dp[i][i] = val[i];
代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <cstdio> 5 #include <bitset> 6 #include <vector> 7 #include <queue> 8 #include <stack> 9 #include <cmath> 10 #include <list> 11 #include <set> 12 #include <map> 13 #define rep(i,a,b) for(int i = a;i <= b;++ i) 14 #define per(i,a,b) for(int i = a;i >= b;-- i) 15 #define mem(a,b) memset((a),(b),sizeof((a))) 16 #define FIN freopen("in.txt","r",stdin) 17 #define FOUT freopen("out.txt","w",stdout) 18 #define IO ios_base::sync_with_stdio(0),cin.tie(0) 19 #define mid ((l+r)>>1) 20 #define ls (id<<1) 21 #define rs ((id<<1)|1) 22 #define N 2005 23 #define INF 0x3f3f3f3f 24 #define INFF ((1LL<<62)-1) 25 typedef long long LL; 26 using namespace std; 27 28 int n, a[N], dp[N][N]; 29 int main() 30 {IO; 31 //FIN; 32 while(cin >> n){ 33 mem(dp, 0); 34 rep(i, 1, n){ 35 cin >> a[i]; 36 dp[i][i] = a[i]; 37 } 38 per(i, n, 1){ 39 rep(j, i, n) 40 dp[i][j] = max(dp[i+1][j]+a[i]*(n-(j-i)), dp[i][j-1]+a[j]*(n-(j-i))); 41 } 42 cout << dp[1][n] << endl; 43 } 44 return 0; 45 }