码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-10-27 17:09:51      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:name   any   int   namespace   取石子   tput   can   scan   names   

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按照最优策略取得最少。

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

标签:name   any   int   namespace   取石子   tput   can   scan   names   

原文地址:https://www.cnblogs.com/ellery/p/11747650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!