BZOJ2101: [Usaco2010 Dec]Treasure Chest 藏宝箱

来源:互联网 发布:js判断json是否存在 编辑:程序博客网 时间:2024/04/30 03:08

Portal

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

HINT

(贝西最好的取法是先取35,然后邦妮会取30,贝西再取25,邦妮最后取10)

看别人写的题解,全都是n2!!?
。。表示我看了这个式子还想了半天为什么是对的。。
f[i,j]=sum[i,j]min(f[i+1,j],f[i,j1])
f[i,j]表示,从ij,先手取者的最大获利。
这样改了以后不是会导致先后手变化吗?想了半天。。发现原来自己蠢。
这相当于是模拟一个逆过程,由内向外推,而实际上是由外向内取。所以无论如何,当前取得都表示为先手,然后先后手转换,减去别人作为先手获利最大值的相对较小值。

空间被卡了过不了。考虑一下区间dp的写法。
for(len=1,len<=n,len++)
for(i=1,i+len1<=n;i++)
       f[i,len]=sum[i,i+len1]min(f[i,len1],f[i+1,len1])
然后我们发现第二维并没有用。删去没有影响,空间就可以少一个n,就可以过了。

【代码】

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#define N 5005using namespace std;typedef long long ll;int read(){    int x=0,f=1;char ch=getchar();    while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}    while(isdigit(ch)){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}    return x*f;}int n;int f[N],sum[N];void Input_Init(){    n=read();    for(int i=1;i<=n;i++) sum[i]=read()+sum[i-1];}void DP(){    for(int len=1;len<=n;len++)    for(int i=1;i+len-1<=n;i++)        f[i]=sum[i+len-1]-sum[i-1]-min(f[i+1],f[i]);    printf("%d\n",f[1]); }int main(){    Input_Init();    DP();    return 0;}
0 0