HDU 4597 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

題解

感謝訊哥給我們講ACM,三生有幸

ACM之博弈問題
令勝負值爲先手得分減去後手得分
則先手的目標是勝負值越大越好
後手的目標則是該數值越小越好

/**
*一個簡單博弈論問題,用到了負值最大函數(DFS)+記憶化搜索(dp)
*/
#include<cstdio>
#include<cstring>
#include<numeric>
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;i<N;i++)scanf("%d",&A[i]);
    for(int i=0;i<N;i++)scanf("%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;
}
發佈了40 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章