https://cn.vjudge.net/problem/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 Nspace 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
题意:有一个长度为N的整数序列,Alice和Bob轮流取数,Alice先取。每次玩家只能从左端或者右端取一个或多个数,但不能两端都取。所有数都被取走后游戏结束,然后统计每个人取走的所有数之和,作为各自的得分。两个人采取的策略都是让自己的得分尽量高,并且两个人都足够聪明。求最后结束游戏后先手和后手的得分的差值。
题解:区间dp dp[i][j]表示的是在区间 i-j 中先手的最大得分。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
int a[105],dp[105][105],sum[105];
bool vis[105][105];
int dfs(int l,int r){
if(vis[l][r]) return dp[l][r];
if(l>r) return 0;
vis[l][r]=true;
int ans=-INF;
for(int i=1;i<=r-l+1;i++){//取多少
ans=max(ans,sum[r]-sum[l-1]-min(dfs(l+i,r),dfs(l,r-i)));
}
return dp[l][r]=ans;
}
int main(){
int T,n;
int cas=0;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
}
printf("Case %d: %d\n",++cas,2*dfs(1,n)-sum[n]);
}
return 0;
}