| Time Limit: 2 second(s) | Memory Limit: 32 MB |
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 |
import java.util.*;
public class Main {
static int T,n,M=10000000;
static int[] aa=new int[105];
static int[] ss=new int[105];
static int[][][] dp=new int[2][105][105];
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
T=in.nextInt();
for(int t=1;t<=T;t++)
{
n=in.nextInt();
for(int i=1;i<=n;i++)
{
aa[i]=in.nextInt();
ss[i]=ss[i-1]+aa[i];
}
for(int len=1;len<=n;len++)
for(int i=1;i+len-1<=n;i++)
{
int j=i+len-1;
dp[0][i][j]=-M;dp[1][i][j]=M;
for(int k=1;k<=len;k++)
{
dp[0][i][j]=Math.max(dp[0][i][j],dp[1][i+k][j]+ss[i+k-1]-ss[i-1]);
dp[0][i][j]=Math.max(dp[0][i][j],dp[1][i][j-k]+ss[j]-ss[j-k]);
dp[1][i][j]=Math.min(dp[1][i][j],dp[0][i+k][j]-ss[i+k-1]+ss[i-1]);
dp[1][i][j]=Math.min(dp[1][i][j],dp[0][i][j-k]-ss[j]+ss[j-k]);
}
}
System.out.println("Case "+t+": "+dp[0][1][n]);
}
}
}
方法二
import java.util.*;
public class Main {
static int T,n,sum,M=10000000,ans;
static int[] aa=new int[105];
static int[] ss=new int[105];
static int[][] dp=new int[105][105];
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
T=in.nextInt();
for(int t=1;t<=T;t++)
{
n=in.nextInt();
for(int i=1;i<=n;i++)
{
aa[i]=in.nextInt();
ss[i]=ss[i-1]+aa[i];
}
for(int len=1;len<=n;len++)
for(int i=1;i+len-1<=n;i++)
{
int j=i+len-1,sum=ss[j]-ss[i-1];
dp[i][j]=-M;
for(int k=1;k<=len;k++)
{
dp[i][j]=Math.max(dp[i][j],sum-dp[i+k][j]);
dp[i][j]=Math.max(dp[i][j],sum-dp[i][j-k]);
}
}
ans=dp[1][n]*2-ss[n];
System.out.println("Case "+t+": "+ans);
}
}
}
本文介绍了一个两人轮流从两端取数的博弈游戏,并提供了两种求解最优策略的方法。一种方法通过三维动态规划数组来追踪每一步的最佳选择;另一种方法则简化了状态转移方程,仅使用二维数组实现。

488

被折叠的 条评论
为什么被折叠?



