Light OJ_1031 Easy Game

轻触即可提交代码

Time limit            2000 ms

Memory limit      32768 kB

Source               Special Thanks: Jane Alam Jan (Dataset)

题目要求:

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

 

这是一个博弈的题目,给出一个数列,两人轮流取数, 取完结束。每次可以取好多个数,但是只能从首或者尾为起点取连续的若干个。问最后先手手里的数与后手的数最大差值是多少?

第一次做的时候连题都没看懂,自己还是太cai了

后来发现其实是区间dp的板子题(据说区间dp都是板子题)

枚举长度、起点、终点,使大区间变成小区间,然后比较得到最优解

数组dp[i][j]表示从编号i取到编号j二者的差值

枚举区间断点k,假设先手取[sta, k] 或者 [k+1, end]取最大值,对剩下部分用先手取到的区间和减去就好,因为下一轮对方就是先手了

下面是代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int n;
int a[111];
int sum[111];
int dp[111][111];//表示区间i~j上A比B多的分数值 
 
int main()
{
	int t,test=1;
	scanf("%d",&t);
	while(t--){
		memset(a,0,sizeof(a));
		memset(dp,0,sizeof(dp));
		memset(sum,0,sizeof(sum));
		
		scanf("%d",&n);
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
			sum[i]=sum[i-1]+a[i];
			dp[i][i]=a[i];
		}
		//区间dp  由大区间到小区间 
		for(int len=1;len<=n;len++){//枚举区间长度 
			for(int sta=1;sta+len<=n;sta++){//枚举起点 
				int end=sta+len;//终点 
				dp[sta][end]=sum[end]-sum[sta-1];//sum[j]-sum[i]==区间i+1到j的和 
				for(int k=sta;k<end;k++){//枚举断点 
					//从左到右的最优方案 maxt 
					//sum-dp 是因为下一轮对方是先手,自己暂时取不到了 
					int maxt=max(sum[k]-sum[sta-1]-dp[k+1][end],sum[end]-sum[k]-dp[sta][k]);
					dp[sta][end]=max(dp[sta][end],maxt);
				}
			}
		}
			
		printf("Case %d: %d\n",test,dp[1][n]);
		test++;
	}
	return 0;
 } 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值