码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 4597 Play Game【记忆化搜索】

时间:2015-01-21 13:27:36      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

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 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
 分析:一个很好的记忆化搜索题,让我对记忆化搜索又有了新的认识。
 这道题还可以有区间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;
}

 

hdu 4597 Play Game【记忆化搜索】

标签:

原文地址:http://blog.csdn.net/letterwuyu/article/details/42966933

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!