Treats for the Cows
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5874 | Accepted: 3049 |
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个数,可以把这个数列,当成是一个双向队列,可以从队头和队尾出队。
如果这个数是第i个出队的,那么这个数乘以i,求所有数出队之后,得到的最大的总和。
思路:
区间DP
num[i]代表数列。
dp[i][j]代表第i~第j个数组成的队列完全出队的最大和。
那么,dp[i][j+1],在增加了一个数字之后,可能有以下两种情况:
1. 先出i,然后剩下的数,就是i+1~j+1了。那么这个数列最大和的出队方案,和dp[i+1][j+1]的出队方案是一样的,只不过,所有数都延后一次出队,因为第一个让i出队了。
所以,最终的总和应该是num[i]+dp[i+1][j+1]+num[i+1]+...+num[j+1]
2. 先出j+1,然后剩下的是i~j。自然,剩下的数也和dp[i][j]的出队方案一样。
总和为num[j+1]+dp[i][j]+num[i]+...+num[j]
不妨用一个sum[i]数组,记录num[0~i]的和。这样能用前缀和来有效降低时间复杂度。
所以,状态转移方程为:
dp[i][j]=max(dp[i+1][j],dp[i][j-1])+sum[j]-sum[i-1];
AC代码:
#include<cstdio>
#include<algorithm>
using namespace std;
int dp[2002][2002];
int num[2002];
int sum[2002];
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=0;i<n;i++)
{
scanf("%d",&num[i]);
if(i==0)sum[i]=num[i];
else sum[i]=sum[i-1]+num[i];
dp[i][i]=num[i];
}
for(int i=1;i<n;i++)
{
for(int j=0;j<n-i;j++)
{
dp[j][j+i]=max(dp[j+1][j+i],dp[j][j+i-1])+sum[j+i]-sum[j-1];
}
}
printf("%d\n",dp[0][n-1]);
/*
for(int i=1;i<n;i++)
{
for(int j=0;j<n-i;j++)
{
printf("%d ",dp[j][j+i]);
}
printf("\n");
}*/
}
return 0;
}
伏见老贼又开新坑,祝贺《工口漫画老师》继漫画化之后又动画化并取得佳绩~(还是觉得妖精好可怜,求给个好结局吧)