Play Game(记忆化搜索)

              http://acm.hdu.edu.cn/showproblem.php?pid=4597
Problem Description
  Alice and Bob are playing a game. There are two piles of cards. There are N cards in each pile, and each card has a score. They take turns to pick up the top or bottom card from either pile, and the score of the card will be added to his total score. Alice and Bob are both clever enough, and will pick up cards to get as many scores as possible. Do you know how many scores can Alice get if he picks up first?
Input
  The first line contains an integer T (T≤100), indicating the number of cases.
  Each case contains 3 lines. The first line is the N (N≤20). The second line contains N integer ai (1≤ai≤10000). The third line contains N integer bi (1≤bi≤10000).
Output
  For each case, output an integer, indicating the most score Alice can get.
Sample Input
  2
  1
  23
  53
  3
  10 100 20
  2 4 3
Sample Output
  53
  105

题意

有两堆N张牌分数卡片。轮流从两堆牌中挑选最上面或最下面的一张牌,最优情况下,先手得到的最高分。

思路

  dp[la][ra][lb][rb]表示当前的第一堆牌顶部为第la张,底部为第ra张时,第二堆同理,先手最多能获得的分数,它的状态与前面的四种状态有关:
  max(sum-dp[la+1][ra][lb][rb],sum-dp[la][ra-1][lb][rb],sum-dp[la][ra][lb+1][rb],sum-dp[la-1][ra][lb][rb-1]),其中sum是当前总分数,简单说一下sum-dp[la+1][ra][lb][rb]的含义,既然我们认为dp[la][ra][lb][rb]表示Alice最多能获得的分数,因为都是最优情况,那么他的前一步就表示Bob最多能获得的分数,所以 当前总分数 - Bob 的就是 Alice 的

AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

int dp[24][24][24][24];
int a[24],b[24];	//记录牌的分数
int f(int la,int ra,int lb,int rb,int sum)	//记忆化搜索
{
    if(la>ra&&lb>rb) return 0;	//越界返回0
    if(dp[la][ra][lb][rb]) return dp[la][ra][lb][rb];
    int _max = 0;
    if(la<=ra){
        _max = max(_max,sum - f(la+1,ra,lb,rb,sum-a[la]));	//sum-a[la]更新当前最大分数
        _max = max(_max,sum - f(la,ra-1,lb,rb,sum-a[ra]));
    }
    if(lb<=rb){
        _max = max(_max,sum - f(la,ra,lb+1,rb,sum-b[lb]));
        _max = max(_max,sum - f(la,ra,lb,rb-1,sum-b[rb]));
    }
    dp[la][ra][lb][rb] = _max;
    return _max;
}
int main(void)
{
    int t,n;
    cin>>t;
    while(t--){
        memset(dp,0,sizeof(dp));
        scanf("%d",&n);
        int sum = 0;
        for(int i=1;i<=n;i++){
            scanf("%d",a+i);
            sum += a[i];
        }
        for(int i=1;i<=n;i++){
            scanf("%d",b+i);
            sum += b[i];	//当前的最大分数
        }
        printf("%d\n",f(1,n,1,n,sum));
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逃夭丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值