天天看點

【HDU】4597 Play Game(DP+記憶化搜尋)Play Game

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 <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
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;
}
           

繼續閱讀