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 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 optimally.
Sample Input

2

 

4

4 -10 -20 7

 

4

1 2 3 4

Sample Output

Case 1: 7

Case 2: 10

参考题解
题目给一个序列,两个人轮流在序列的两边取任意个数的number,但每次只能从选定的那一边取,问取得数字的和的较大者比较小者多多少?
dp[i][j]表示区间i到j先手最大比后手多多少分,每一段都这么处理,用小段推导大段。

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 105;
int sum[maxn], dp[maxn][maxn];  //dp代表在区间i到j中,先手与后手的最大差距

int main()
{
    int T, n, x;
    scanf("%d", &T);
    for(int cas = 1; cas <= T; cas++)
    {
        cin >> n;
        sum[0] = 0;
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &x);
            sum[i] = sum[i - 1] + x;
        }
        //遍历区间长度,从1到n
        for(int len = 1; len <= n; len++)
            for(int left = 1; left + len - 1 <= n; left++)
            {
                int right = left + len - 1;
                dp[left][right] = sum[right] - sum[left - 1];
                for(int mid = left; mid < right; mid++)
                {
                    //遍历所有可行的情况sum之差代表先手所选择的的数字之和,剩下的便应该是第二个人取数字然后这样在剩下区间中
                    //轮流取数,但是,在第一个人取完数字时候,就相当于到了第二个人先手,所以应该减去第二个人取时候的最大差距
                    int t = max(sum[mid] - sum[left - 1] - dp[mid + 1][right], sum[right] - sum[mid] - dp[left][mid]);
                    dp[left][right] = max(dp[left][right], t);
                }
            }
       printf("Case %d: %d\n", cas, dp[1][n]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40788897/article/details/84772308