UVA 10891 - Game of Sum(区间dp)

Problem E
Game of Sum
Input File: 
e.in

Output: Standard Output

 

This is a two player game. Initially there are n integer numbers in an array and players 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

The input consists of a number of cases. Each case starts with a line specifying the integer n (0 < n ≤100), the number of elements in the array. After that, n numbers are given for the game. Input is terminated by a line where n=0.

 

Output

For each test case, print a number, which represents the maximum difference that the first player obtained after playing this game optimally.

 

Sample Input                                Output for Sample Input

4

4 -10 -20 7

4

1 2 3 4

0

7

10


题意:给定n个石头,每个石头有一个分数,现在小伙伴A和小伙伴B进行一个游戏,小伙伴A先手,每个人每次可以选择从头或从尾取k个石头,要求出如果两个人每次都按自己最好的情况去取,最后两个人分数差是多少。

思路:经典的区间dp。用i,j表示区间i,j的情况。用k表示取k个石头,递推的方法没想出来,用记忆化搜索写的。由于可能有正有负,所以多开了一个VIS数组来表示当前区间之前查找过了没有,如果查找过了直接把return dp[i][j]。

代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

int n, num[105], sum[105][105], dp[105][105], vis[105][105];

int dfs(int i, int j) {
    int ans = -999999999;
    if (i > j) 
	return 0;
    if (vis[i][j])//记忆化搜索。
	return dp[i][j];
    vis[i][j] = 1;
    for (int k = 1; k <= j - i + 1; k ++) {
	ans = max(ans, sum[i][j] - min(dfs(i + k, j), dfs(i, j - k)));
    }
    dp[i][j] = ans;
    return ans;
}

int main() {
    while (~scanf("%d", &n) && n) {
	memset(dp, 0, sizeof(dp));
	memset(vis, 0, sizeof(vis));
	for (int i = 0; i < n; i ++)
	    scanf("%d", &num[i]);
	for (int i = 0; i < n; i ++) {
	    int numm = 0;
	    for (int j = i; j < n; j ++) {
		numm += num[j];
		sum[i][j] = numm;
	    }
	}
	printf("%d\n", 2 * dfs(0, n - 1) - sum[0][n - 1]);
    }
    return 0;
}



你可能感兴趣的:(UVA 10891 - Game of Sum(区间dp))