lightoj 1031 - Easy Game 【区间dp】

题目链接:lightoj 1031 - Easy Game

1031 - Easy Game
PDF (English) Statistics Forum
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 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
Output for Sample Input
2

4
4 -10 -20 7

4
1 2 3 4
Case 1: 7
Case 2: 10

题意:给定n个数,两个人轮流取,每次只能从左或者右端点取任意个连续的数。直到所有数取完游戏结束,最后得分为所取数之和。假设两个人都足够聪明,问你最后最大的分数差。

思路:dp[i][j]表示区间[i, j]取数可以得到的最优解。然后枚举区间端点O(n^3)转移就好了。

AC代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
#define CLR(a, b) memset(a, (b), sizeof(a))
using namespace std;
typedef long long LL;
const int MAXN = 3*1e5 +10;
const int MOD = 1e6 + 7;
int sum[110], a[110];
int dp[110][110];
int M;
int DFS(int l, int r) {
    if(l > r) return 0;
    if(l == r) return dp[l][r] = a[l];
    if(dp[l][r] != M) return dp[l][r];
    dp[l][r] = sum[r] - sum[l-1];
    for(int i = l; i <= r; i++) {
        dp[l][r] = max(dp[l][r], sum[r] - sum[i-1] - DFS(l, i-1));
        dp[l][r] = max(dp[l][r], sum[i] - sum[l-1] - DFS(i+1, r));
    }
    return dp[l][r];
}
int main()
{
    int t, kcase = 1;
    scanf("%d", &t);
    while(t--) {
        int n; scanf("%d", &n); sum[0] = 0;
        for(int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
            sum[i] = sum[i-1] + a[i];
        }
        M = -sum[n] - 10;
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                dp[i][j] = M;
            }
        }
        printf("Case %d: %d\n", kcase++, DFS(1, n));
    }
    return 0;
}

你可能感兴趣的:(lightoj 1031 - Easy Game 【区间dp】)