[BZOJ2101] [Usaco2010 Dec]Treasure Chest 藏宝箱

题目描述

Description

Bessie and Bonnie have found a treasure chest full of marvelous gold coins! Being cows, though, they can't just walk into a store and buy stuff, so instead they decide to have some fun with the coins. The N (1 <= N <= 5,000) coins, each with some value C_i (1 <= C_i <= 5,000) are placed in a straight line. Bessie and Bonnie take turns, and for each cow's turn, she takes exactly one coin off of either the left end or the right end of the line. The game ends when there are no coins left. Bessie and Bonnie are each trying to get as much wealth as possible for themselves. Bessie goes first. Help her figure out the maximum value she can win, assuming that both cows play optimally. Consider a game in which four coins are lined up with these values: 30 25 10 35 Consider this game sequence: Bessie Bonnie New Coin Player Side CoinValue Total Total Line Bessie Right 35 35 0 30 25 10 Bonnie Left 30 35 30 25 10 Bessie Left 25 60 30 10 Bonnie Right 10 60 40 -- This is the best game Bessie can play.
贝西和邦妮找到了一个藏宝箱,里面都是金币!但是身为两头牛,她们不能到商店里把金币换成好吃的东西,于是她们只能用这些金币来玩游戏了。
藏宝箱里一共有N枚金币,第i枚金币的价值是Ci。贝西和邦妮把金币排成一条直线,她们轮流取金币,看谁取到的钱最多。贝西先取,每次只能取一枚金币,而且只能选择取直线两头的金币,不能取走中间的金币。当所有金币取完之后,游戏就结束了。
贝西和邦妮都是非常聪明的,她们会采用最好的办法让自己取到的金币最多。请帮助贝西计算一下,她能拿到多少钱?

Input

Line 1: A single integer: N * Lines 2..N+1: Line i+1 contains a single integer: C_i
第一行:单个整数N,表示硬币的数量,1<=N≤5000
第二行到第N+1行:第i+l行有一个整数Ci,代表第i块硬币的价值,1≤Ci≤5000

Output

Line 1: A single integer, which is the greatest total value Bessie can win if both cows play optimally.
第一行:单个整数,表示如果双方都按最优策略玩游戏,先手可以拿到的最大价值

Sample Input

4
30
25
10
35

Sample Output

60

题目分析

先列出简单的DP方程
表示 将区间i~j都取走 先手能获得的最大价值
那么
但这么转移空间复杂度是 64MB 开不下
我们把上面的DP方程换个形式
表示 将区间i~(i+len)都取走 先手能获得的最大价值
那么
把第二维提前 发现 只和有关
这样的话就能进行滚动数组了

#include <cstdio>
#include <cstring>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int n;
int f[5010],a[5010],sum[5010];
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    for(int i=1;i<=n;i++) f[i]=a[i],sum[i]=sum[i-1]+a[i];
    for(int len=1;len<=n;len++)
        for(int l=1,r;(r=len+l)<=n;l++)
            f[l]=max(a[l]+sum[r]-sum[l]-f[l+1],a[r]+sum[r-1]-sum[l-1]-f[l]);
    printf("%d",f[1]);
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注