1. 程式人生 > >LightOJ - 1031 - Easy Game(區間dp )

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;
}