LightOJ - 1031 Easy Game 区间dp

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个石头,每个石头有一个分数,现在小伙伴A和小伙伴B进行一个游戏,小伙伴A先手,每个人每次可以选择从头或从尾取k个石头,要求出如果两个人每次都按自己最好的情况去取,最后两个人分数差是多少。

题解:dp[i][j] 代表 先手 - 后手 得到的最大值  对于每个区间,枚举区间每个点,分先取左边还是右边,另一部分就是后手对应的先手了,需要减去,写的时候居然符号搞错了...

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100+11;
#define eps 1e-10
#define INF 0x3f3f3f3f
int n;
int a[N];
int sum[N];
int dp[N][N];
int main()
{
	int x;
	int nn=1;
	int T;
	scanf("%d",&T);
	while(T--) {
		scanf("%d", &n);
		memset(dp,-INF,sizeof(dp));
		memset(sum,0,sizeof(sum));
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&x);
			sum[i]=sum[i-1]+x;
			dp[i][i]=x;
		}
		for(int len=2;len<=n;len++)
		{
			for(int l=1;l<=n-len+1;l++)
			{
				int r=l+len-1;
				dp[l][r]=sum[r]-sum[l-1];
				for(int k=l;k<r;k++)
					dp[l][r]=max(dp[l][r],max(sum[r]-sum[k]-dp[l][k],sum[k]-sum[l-1]-dp[k+1][r]));
			}
		}
		printf("Case %d: %d\n",nn++,dp[1][n]);
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值