hdu 4597 Play Game【记忆化搜索】

Play Game

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 805    Accepted Submission(s): 464


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 a i (1≤a i≤10000). The third line contains N integer b i (1≤b i≤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
 分析:一个很好的记忆化搜索题,让我对记忆化搜索又有了新的认识。
 这道题还可以有区间dp做,但应该说记忆化搜索更合适,我只说记忆化
搜索。
首先先分析题意,再结合代码。
每一个人的当前取法有四种即4个端,所以一共有4中状态转移方程,而当前的取值便为这4个方程中结果最大的值。
由于题目中的两个人都是聪明的,我唯一的区别就是谁先谁后,因此这两个人的取牌策略是相同的,这是关键的
地方,不然解决不了。所以会看到我的代码中当求当前值是,是取当前余下的牌的和减去下一个人取牌的时候
最优策略值,然后去这4中情况中的最大值,这里有点绕,还是看代码吧。
代码示例:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#define maxh 30
using namespace std;
int dp[maxh][maxh][maxh][maxh];
int sum1[maxh],sum2[maxh];
int max(int a,int b)
{
    return a>b?a:b;
}   
int dfs(int h1,int t1,int h2,int t2)
{
    if(dp[h1][t1][h2][t2]!=-1)
    return dp[h1][t1][h2][t2];
    dp[h1][t1][h2][t2]=0;
    //4中状态转移方程
    if(h1<=t1)
    dp[h1][t1][h2][t2]=sum1[t1]-sum1[h1-1]+sum2[t2]-sum2[h2-1]-dfs(h1+1,t1,h2,t2);//余下的牌的总和减去下一个人的最优策略值
    if(h1<=t1)
    dp[h1][t1][h2][t2]=max(dp[h1][t1][h2][t2],sum1[t1]-sum1[h1-1]+sum2[t2]-sum2[h2-1]-dfs(h1,t1-1,h2,t2));
    if(h2<=t2)
    dp[h1][t1][h2][t2]=max(dp[h1][t1][h2][t2],sum1[t1]-sum1[h1-1]+sum2[t2]-sum2[h2-1]-dfs(h1,t1,h2+1,t2));
    if(h2<=t2)
    dp[h1][t1][h2][t2]=max(dp[h1][t1][h2][t2],sum1[t1]-sum1[h1-1]+sum2[t2]-sum2[h2-1]-dfs(h1,t1,h2,t2-1));
//4中取最优
    return dp[h1][t1][h2][t2];
}
int main()
{
    int T,n,x;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        sum1[0]=sum2[0]=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&x);
            sum1[i]=sum1[i-1]+x;
        }
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&x);
            sum2[i]=sum2[i-1]+x;
        }
        memset(dp,-1,sizeof(dp));
        printf("%d\n",dfs(1,n,1,n));
    }
    return 0;
}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值