天天看點

愛麗絲和鮑勃正在玩遊戲。 有兩堆牌。 每一堆都有N張牌,每張牌都有一張分數。 他們輪流從任意一堆拿起頂部或底部牌,并且卡的分數将被添加到他的總分中。 愛麗絲和鮑勃都非常聰明,并且會拿起卡片以獲得盡可能

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≤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[la][ra][lb][rb]記錄的是在a的區間隻剩下la~ra,b的區間隻剩下lb~rb的時候,Alice能得到的最大值

那麼隻需要考慮四種不同的取法并從中取得最優的方案,sum-(Alice上一個狀态中Bob拿的值)中取最大

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
int dp[30][30][30][30];
int a[30];
int b[30];
int dfs(int la,int ra,int lb,int rb,int sum)
{
      int maxn=0;
      if(la>ra&&lb>rb)return 0;
      if(dp[la][ra][lb][rb]) return dp[la][ra][lb][rb];
      if(la<=ra)
      {
          maxn=max(maxn,sum-dfs(la+1,ra,lb,rb,sum-a[la]));  //其實就是用總共數的和,減去偶數次抽的數的和。
          maxn=max(maxn,sum-dfs(la,ra-1,lb,rb,sum-a[ra]));
      }
      if(lb<=rb)
      {
          maxn=max(maxn,sum-dfs(la,ra,lb+1,rb,sum-b[lb]));
          maxn=max(maxn,sum-dfs(la,ra,lb,rb-1,sum-b[rb]));
      }
     dp[la][ra][lb][rb]=maxn;
      return maxn;
}
int main()
{
    int n,x;
    cin>>n;
    while(n--)
    {
        memset(dp,0,sizeof(dp));
        int sum=0;
        cin>>x;
        for(int i=1;i<=x;i++)
        {
            cin>>a[i];
            sum+=a[i];
        }
        for(int i=1;i<=x;i++)
        {
            cin>>b[i];
            sum+=b[i];
        }
    cout<<dfs(1,x,1,x,sum)<<endl;
    }
}
           

繼續閱讀