转载请注明出处:http://blog.csdn.net/u012860063
题意
Alice和Bob玩一个游戏,有两个长度为N的正整数数字序列,每次他们两个仅仅能从当中一个序列,选择两端中的一个拿走。他们都希望能够拿到尽量大
的数字之和,而且他们都足够聪明。每次都选择最优策略。Alice先选择,问
终于Alice拿到的数字总和是多少?
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).
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
Source
代码例如以下:
#include <cstdio>
#include <cstring>
#define MAX 20+10
int s1[MAX], s2[MAX], sum1[MAX], sum2[MAX];
int dp[MAX][MAX][MAX][MAX];
//dp[a][b][i][j]表示当前玩家从s1的a~b,s2的i~j能获得的最大价值
int max(int a, int b)
{
if(a > b)
return a;
return b;
}
int dfs(int a, int b, int i, int j)
{
if(dp[a][b][i][j])
return dp[a][b][i][j];
if(a > b && i > j)
return 0;
int max1 = 0;
int max2 = 0;
if(a <= b)
max1=max(s1[a]+dfs(a+1,b,i,j),s1[b]+dfs(a,b-1,i,j));//取前后中值大的
if(i <= j)
max2=max(s2[i]+dfs(a,b,i+1,j),s2[j]+dfs(a,b,i,j-1));//取前后中值大的
dp[a][b][i][j]=sum1[b]-sum1[a-1]+sum2[j]-sum2[i-1]-max(max1,max2);
//区间和减去对手所取的剩下的就为当前玩家的
return dp[a][b][i][j];
}
int main()
{
int t, n;
while(~scanf("%d",&t))
{
while(t--)
{
memset(dp,0,sizeof(dp));
memset(sum1,0,sizeof(sum1));
memset(sum2,0,sizeof(sum2));
int ans = 0;
int i, j;
scanf("%d",&n);
for(i = 1; i <= n; i++)
{
scanf("%d",&s1[i]);
sum1[i] = sum1[i-1]+s1[i];
}
for(i = 1; i <= n ; i++)
{
scanf("%d",&s2[i]);
sum2[i] = sum2[i-1]+s2[i];
}
ans = sum1[n]+sum2[n]-dfs(1,n,1,n);
printf("%d\n",ans);
}
}
return 0;
}