LightOj 1031 区间dp

本文介绍了一种两人博弈游戏的最优策略求解算法。玩家A和B轮流从数组两端取整数,目标是使自己的得分最大化,得分等于所取数字之和。通过区间动态规划的方法确定了玩家A能够获得的最大分数优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

F - Easy Game

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



    

   区间dp  摸清套路 以此为模板 

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int dp[1005][1005];
int a[1005];
int sum[1005];
int main(){
	int t,n,kase=1;
	cin>>t;
	while(t--){
		scanf("%d",&n);
		memset(sum,0,sizeof(sum));
		memset(dp,0,sizeof(dp));
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
			sum[i]=sum[i-1]+a[i];
			dp[i][i]=a[i];
		} 
		
		for(int i=1;i<=n;i++){   
		   for(int j=1;j<=n-i;j++){
		   	  int k=j+i;
		   	  dp[j][k]=sum[k]-sum[j-1];
		   	  for(int w=j;w<k;w++){
		   	  	dp[j][k]=max(dp[j][k],max(sum[w]-sum[j-1]-dp[w+1][k],sum[k]-sum[w]-dp[j][w]));
			 }
	     }
	 }
	     printf("Case %d: %d\n",kase++,dp[1][n]);
	}
} 






 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值