lightoj 1031 - Easy Game - dblank

lightoj 1031 - Easy Game

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

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

4 -10 -20 7

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


dp[i][j] = max(dp[i][j], sum[k] - sum[i-1] - dp[k+1][j]);
dp[i][j] = max(dp[i][j], sum[j] - sum[k-1] - dp[i][k-1]);

sum[i]表示前缀和,sum[k] - sum[i-1]表示这一步我取得人取这个区间,减去下个人取得最大价值就是dpk+1,同理右边。

using namespace std;
const int  N = 100 + 10, inf = 0x3f3f3f3f;
const double eps = 1e-10;
typedef long long ll;
typedef pair<int, int> P;
int v[N];
int dp[N][N], sum[N];
int n;
int dfs(int l ,int r)
    if(l>r) return 0;
    if(dp[l][r] != -1)
        return dp[l][r];
    int res = -inf;
    for(int i = l; i<=r; i++)
        res = max(res, sum[i] - sum[l-1] - dfs(i+1, r));
        res = max(res, sum[r] - sum[i-1] - dfs(l, i-1));
    return dp[l][r] = res;
int main()
    int T;
    scanf("%d", &T);
    for(int cas = 1; cas<=T; cas++)
        memset(dp, -1, sizeof(dp));
        scanf("%d", &n);
        sum[0] = 0;
        for(int i = 1; i<=n; i++)
            scanf("%d", &v[i]), sum[i] = sum[i-1] + v[i], dp[i][i] = v[i];
        printf("Case %d: %d\n", cas, dfs(1, n));
    return 0;