【HDU】4597 Play Game(DP+记忆化搜索)

Play Game

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

1、dp[al][ar][bl][br]表示在pile1的数还剩下从al到ar(开区间),pile2的数还剩下bl到br的情况下,先手取得的最大值。那状态转移就最多只有四个方向,比如取pile1的左边那个数,那能获得的最大价值就是,a[al+1] + (suma[ar-1]-suma[al+1]+sumb[br-1]-sumb[bl]-dp[al+1][ar][bl][br])(预处理出pile1的和pile2的前缀和,用剩下的价值减去后手能获得的最大价值)
2、然后记忆化搜索就好了。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int a[30],b[30];
int sum1[30];
int sum2[30];
int dp[30][30][30][30];
int solve(int l1,int r1,int l2,int r2)
{
    if(dp[l1][r1][l2][r2] != -1)return dp[l1][r1][l2][r2];
    if(l1 > r1 && l2 > r2)
        return dp[l1][r1][l2][r2] = 0;
    int ans = 0;
    int sum = 0;
    if(l1 <= r1)
        sum += sum1[r1] - sum1[l1-1];
    if(l2 <= r2)
        sum += sum2[r2] - sum2[l2-1];
    if(l1 <= r1)
    {
        ans = max(ans,sum - solve(l1+1,r1,l2,r2));
        ans = max(ans,sum - solve(l1,r1-1,l2,r2));
    }
    if(l2 <= r2)
    {
        ans = max(ans,sum - solve(l1,r1,l2+1,r2));
        ans = max(ans,sum - solve(l1,r1,l2,r2-1));
    }
    return dp[l1][r1][l2][r2] = ans;
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int n;
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        sum1[0] = sum2[0] = 0;
        for(int i = 1;i <= n;i++)
        {
            scanf("%d",&a[i]);
            sum1[i] = sum1[i-1] + a[i];
        }
        for(int i = 1;i <= n;i++)
        {
            scanf("%d",&b[i]);
            sum2[i] = sum2[i-1] + b[i]; 
        }
        memset(dp,-1,sizeof(dp));
        printf("%d\n",solve(1,n,1,n));
    }
    return 0;
}


你可能感兴趣的:(-专栏-,ACM题解集锦,ACM题解集锦)