hdu4597

Play Game

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


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

思路;我们可以开有个4维数组dp[x1][y1][x2][y2]来记录a数组只剩下x1到y1时,b数组只剩下x2到y2时能获得最大值,其实只要用总和减去Alice上一状态时Bob能获得的最大值。

代码:
#include 
#include 
#include 
#include 
using namespace std;
int dp[25][25][25][25],a[25],b[25];
int dfs(int x1,int y1,int x2,int y2,int sum)
{
    int maxn=0;
    if(x1>y1&&x2>y2)return 0;
    if(dp[x1][y1][x2][y2])return dp[x1][y1][x2][y2];
    if(x1<=y1)
    {
        maxn=max(maxn,sum-dfs(x1+1,y1,x2,y2,sum-a[x1]));
        maxn=max(maxn,sum-dfs(x1,y1-1,x2,y2,sum-a[y1]));
    }
    if(x2<=y2)
    {
        maxn=max(maxn,sum-dfs(x1,y1,x2+1,y2,sum-b[x2]));
        maxn=max(maxn,sum-dfs(x1,y1,x2,y2-1,sum-b[y2]));
    }
    dp[x1][y1][x2][y2]=maxn;
    return maxn;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int n;
        scanf("%d",&n);
        memset(dp,0,sizeof(dp));
        int i;
        int sum=0;
        for(i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        for(i=1;i<=n;i++)
        {
            scanf("%d",&b[i]);
            sum+=b[i];
        }
        int z=dfs(1,n,1,n,sum);
        cout<



你可能感兴趣的:(区间dp)