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
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个物品,每个物品都有价值,每次有个人可以选着从左边或者右边选取一个连续的一些物品获得他们的价值,也可以全部取完。A先手,B后手。问最后A最多可以比B多获得多少价值。
思路:dpi表示选取i区间能获得的最大价值。
于是对于每个区间,我们可以枚举断点k,于是有:

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,同理右边。
可以记忆化搜索。
AC代码:

#include<bits/stdc++.h>
 
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;
}

相关文章

发表新评论