有n个数排成一行,现在A和B两人从两端取任意个数(每次至少取一个,每人都是最佳状态),直到取完所有的数,A先取,求A取得数的和比B大多少?

Description

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 4 digits.

Output

For each test case, print the case number and the maximum difference that the first player obtained after playing this game optima

Sample Input

2

4

4 -10 -20 7

4

1 2 3 4

Output for Sample Input

7

10

代码如下:

思路:

区间DP,dp[i][j] 表示区间i~j A取得数的和比B大多少,那么可以这样分析:对于区间i~j  A先取sum[k]-sum[i-1]或sum[j]-sum[k](只能从两端取),然后该B取了,即对于区间k+1~j和i~k  DP转换为B比A大多少了,所以状态转移方程为 dp[i][j]=max(dp[i][j],max(sum[k]-sum[i-1]-dp[k+1][j],sum[j]-sum[k]-dp[i][k])); 

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
int dp[300][300];
int sum[300];
int a[300];
int main()
{
    int n;
    while(cin>>n&&n)
    {
        memset(sum,0,sizeof(sum));
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
            dp[i][i]=a[i];
        }
        for(int i=1;i<=n;i++)
        {
            sum[i]=sum[i-1]+a[i];
        }
        for(int len=1;len<=n;len++)  //这里要注意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[k]-sum[l-1]-dp[k+1][r],sum[r]-sum[k]-dp[l][k]));
                }
            }
        }
        cout<<dp[1][n]<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/82315886