http://lightoj.com/volume_showproblem.php?problem=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 4digits.
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 | Output for Sample Input |
2
4 4 -10 -20 7
4 1 2 3 4 | Case 1: 7 Case 2: 10 |
用dp[i][j]表示在区间i~j上A比B多的分数值,由于二者都采取最优策略,故可以枚举i~j之间的的数k,取子区间i~k和k+1~j中的最大值(子区间的最大值表示B比A多的分数,因为A取完之后就要改B取了,也是最优的策略),我们就得到了状态转移方程:dp[i][j]=max(dp[i][j],max(sum[k]-sum[i-1]-dp[k+1][j],sum[j]-sum[k]-dp[i][k])) (i<=k<=j);
代码:
#include <stdio.h>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn=105;
int dp[maxn][maxn];
int sum[maxn],a[maxn];
int N;
int main()
{
int T;
int tt=1;
scanf("%d",&T);
while(T--)
{
int a;
scanf("%d",&N);
sum[0]=0;
memset(dp,-0x3f,sizeof(dp));
for(int i=1;i<=N;i++)
{
scanf("%d",&a);
sum[i]=sum[i-1]+a;
dp[i][i]=a;
}
for(int i=N-1;i>=1;i--)
for(int j=i+1;j<=N;j++)
for(int k=i;k<=j;k++)
{
if(k==j)//一次全拿走的情况
{
dp[i][j]=max(dp[i][j],sum[j]-sum[i-1]);
continue;
}
dp[i][j]=max(dp[i][j],max(sum[k]-sum[i-1]-dp[k+1][j],sum[j]-sum[k]-dp[i][k]));
}
printf("Case %d: %d\n",tt++,dp[1][N]);
}
return 0;
}