HihoCoder - 1338 A Game(区间dp)

版权声明:欢迎转载~转载请注明出处! https://blog.csdn.net/riba2534/article/details/83185080

描述

Little Hi and Little Ho are playing a game. There is an integer array in front of them. They take turns (Little Ho goes first) to select a number from either the beginning or the end of the array. The number will be added to the selecter’s score and then be removed from the array.

Given the array what is the maximum score Little Ho can get? Note that Little Hi is smart and he always uses the optimal strategy.

输入

The first line contains an integer N denoting the length of the array. (1 ≤ N ≤ 1000)

The second line contains N integers A1, A2, … AN, denoting the array. (-1000 ≤ Ai ≤ 1000)

输出

Output the maximum score Little Ho can get.

样例输入

4
-1 0 100 2

样例输出

99

思路

给出一个序列,其中包含n个数。现在有两个人每一次可以从序列的首部或者尾部选择一个数,把选择的这个数的值作为自己的得分累加给自己,然后把这个数从序列中删除。当序列中没有元素时结束游戏。现在问其中一个人的最大得分是多少.

由于每次只能从数组首/尾拿走一个数,所以小Hi和小Ho在任何时候面对的残局都只可能是一段连续的子数组A[i..j]。我们不妨用f[i][j]表示当面对A[i..j],先手最多能获得的得分。

如果我们能计算出所有f[i][j]的值,那么显然f[1][n]就是最终答案。

其中i = j的情况f[i][j]的值是很容易计算的:f[i][j]=A[i]。因为只剩下A[i]一个数,先手只能拿走A[i]

对于i < j的情况,先手P需要决策是拿走A[i]还是拿走A[j]?

如果拿走A[i],那么对手Q面对的是A[i+1 .. j],Q最多能获得的得分是f[i+1][j]。而且Q一定会按照得到f[i+1][j]这个得分的方式进行决策。所以先手P最大得分是sum(A[i .. j]) - f[i+1][j]。(A[i][j]的分数和减去P的得分)

同理如果拿走A[j],先手P最大得分会是sum(A[i .. j]) - f[i][j-1]

由于此时先手P可以二选一,所以f[i][j] = max{ sum(A[i .. j]) - f[i+1][j], sum(A[i .. j]) - f[i][j-1] } = sum(A[i .. j]) - min(f[i+1][j], f[i][j-1])

sum[i,j]就是直接求前缀和

代码

#include <bits/stdc++.h>
using namespace std;
#define mem(a, b) memset(a, b, sizeof(a))
const int N = 1e3 + 10;
int sum[N], a[N], dp[N][N];
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &a[i]);
        sum[i] = sum[i - 1] + a[i];
        dp[i][i] = a[i];
    }
    for (int k = 1; k <= n; k++)
    {
        for (int i = 1; i + k <= n; i++)
        {
            int j = i + k;
            dp[i][j] = sum[j] - sum[i - 1] - min(dp[i + 1][j], dp[i][j - 1]);
        }
    }
    printf("%d\n", dp[1][n]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/riba2534/article/details/83185080
今日推荐