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
题目大意:
给定一行数字,两人轮流拿数字。每一次取数字可以选择从左侧或者右侧拿一个或者连续拿多个数字。数字被取完则游戏结束。每个人的得分等于他拿的数字之和,若A先拿,B后拿,问在两人都足够聪明的前提下,A比B高多少分。
核心思想:
记忆化搜索。
dp[i][[j]表示某人面对第i个数至第j个数时,可以获得的最大分差。(是分差不是分数!)
枚举每一种取法,选择最优值。
详见代码!
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int N=110;
int a[N],dp[N][N];
int dfs(int l,int r)
{
if(dp[l][r]!=-inf)//搜过dp[l][r],直接返回
return dp[l][r];
if(l>r)
return dp[l][r]=0;
if(l==r)
return dp[l][r]=a[l];
int sum=0,mx=-inf;
//从左侧拿
for(int i=l; i<=r; i++)
{
sum+=a[i];
//下一次dfs是对方的分数,对于我而言是负的
mx=max(mx,sum-dfs(i+1,r));
}
sum=0;
//从右侧拿
for(int i=r; i>=l; i--)
{
sum+=a[i];
mx=max(mx,sum-dfs(l,i-1));
}
return dp[l][r]=mx;//返回前记忆下
}
int main()
{
int T,ca=0;
cin>>T;
while(T--)
{
int n;
cin>>n;
//初始化,如果用memset(dp,inf,sizeof(dp))
//那么dp[i][j]并不和inf完全相等
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
dp[i][j]=-inf;
//输入
for(int i=1; i<=n; i++)
scanf("%d",&a[i]);
//输出
printf("Case %d: %d\n",++ca,dfs(1,n));
}
return 0;
}