Easy Game LightOJ - 1031(记忆化搜索+博弈)

You are playing a two player game. Initially there are n integer numbers in an array and player A and B get chance to take them alternatively. Each player can take one or more numbers from the left or right end of the array but cannot take from both ends at a time. He can take as many consecutive numbers as he wants during his time. The game ends when all numbers are taken from the array by the players. The point of each player is calculated by the summation of the numbers, which he has taken. Each player tries to achieve more points from other. If both players play optimally and player A starts the game then how much more point can player A get than player B?


Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case contains a blank line and an integer N (1 ≤ N ≤ 100) denoting the size of the array. The next line contains N space separated integers. You may assume that no number will contain more than 4 digits.

Output

For each test case, print the case number and the maximum difference that the first player obtained after playing this game optimally.

Sample Input

2

4

4 -10 -20 7

4

1 2 3 4

Sample Output

Case 1: 7

Case 2: 10

#include<iostream>
#include<string.h>
using namespace std;
int dp[109][109];
int a[10009];


int dfs(int l,int r){//dfs函数:先手比后手多拿多少 
    if(l>r) return 0;
    if(dp[l][r]!=-1) return dp[l][r];
    //拿左边:
    int ans=-0x3f3f3f3f;
    for(int i=l+1;i<=r+1;i++){
        int tem=0;
        for(int j=l;j<i;j++) tem+=a[j];
        ans=max(ans,tem-dfs(i,r));
    }
    // 拿右边:
    for(int i=r-1;i>=l-1;i--){
        int tem=0;
        for(int j=r;j>i;j--) tem+=a[j];
        ans=max(ans,tem-dfs(l,i));
    } 
//    printf("l:%d r:%d dp:%d\n",l,r,ans);
    return dp[l][r]=ans;
}



int main(){
    int t;
    scanf("%d",&t);
    int ct=1;
    while(t--){
        int n;
        scanf("%d",&n);
        printf("Case %d: ",ct++);
        memset(dp,-1,sizeof(dp));
        for(int i=1;i<=n;i++) scanf("%d",&a[i]);
        cout<<dfs(1,n)<<endl;
    }
} 
 
A取石子的最优策略,肯定是取完以后,B按照最优策略取得最少。B取石子,肯定是取完之后,A按照最优策略取得最少。

猜你喜欢

转载自www.cnblogs.com/ellery/p/11747650.html