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
感谢讯哥给我们讲ACM,三生有幸
ACM之博弈问题
令胜负值为先手得分减去后手得分
则先手的目标是胜负值越大越好
后手的目标则是该数值越小越好
/**
*一个简单博弈论问题,用到了负值最大函数(DFS)+记忆化搜索(dp)
*/
#include
#include
#include
const int INF = 100000000;
int N;
int A[21],B[21];
int dp[21][21][21][21];//记忆化搜索时保存数据的数组
//负值最大函数
//negaMax()可以求出一个胜负值,其中胜负值=先手得分-后手得分
int negaMax(int depth,int al,int ar,int bl,int br){
if(depth >= N + N)return 0;
int ret = -INF;//保持当前最大可以得到的分数
int v = 0;//保存当前得到的分数
if(dp[al][ar][bl][br])return dp[al][ar][bl][br];//记录下状态,记忆化搜索
//一共四种选择
if(al<=ar){
/*(A[al]-(后手得分-先手得分))=(A[al]+先手得分-后手得分)=选定A[al]后,
*当前的negaMax()(即先手得分-后手得分),下面的同理
*/
v = A[al] - negaMax(depth+1,al+1,ar,bl,br);
if(v>ret)ret = v;
if(al!=ar){
v = A[ar] - negaMax(depth+1,al,ar-1,bl,br);
if(v>ret)ret = v;
}
}
if(bl<=br){
v = B[bl] - negaMax(depth+1,al,ar,bl+1,br);
if(v>ret)ret = v;
if(bl!=br){
v = B[br] - negaMax(depth+1,al,ar,bl,br-1);
if(v>ret)ret = v;
}
}
return dp[al][ar][bl][br] = ret;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
for(int i=0;iscanf("%d",&A[i]);
for(int i=0;iscanf("%d",&B[i]);
int sum = std::accumulate(A,A+N,0);//stl中的accumulate()函数
sum += std::accumulate(B,B+N,0);
memset(dp,0,sizeof(dp));
//negaMax()=先手得分-后手得分
//先手得分-后手得分+sum=先手得分+sum-后手得分
//所以,先手得分=(negaMax()+sum)/2,其中sum=先手得分+后手得分
printf("%d\n",(negaMax(0,0,N-1,0,N-1)+sum)/2);
}
return 0;
}