Game of Sum
Time Limit: 3000MS Memory Limit: Unknown 64bit IO Format: %lld & %llu
Submit Status
Description
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 rst player
obtained after playing this game optimally.
Sample Input
4
4 -10 -20 7
4
1 2 3 4
0
Sample Output
7
10
解析:经典的区间dp
同 HDU 4597 Play Game (博弈 + 区间dp)
dp[l][r]表示从区间还剩l~r时能去到的最大值
sum[i]表示从区间起始点到当前点的所有数字和
每次取都有四种情况:
从序列最左端取
从序列最右端取
因此,在选取数字个数k(其中0<=k<=r-i+1)给定的情况下,dp[l][r]就由
dp[l+k][r]
dp[l][r-k]
转移而来
针对当前是A取,则上一次则是B取,因为l~r区间的总数sum[r] - sum[l-1]是固定的,欲使A取得最大的,即A要选取上次B的最小选择进行状态转移,即
dp[l][r] = (sum[r] - sum[l-1]) - min{dp[l+k][r], dp[l][r-k]]}
由于重复状态有很多,再加个记忆化
AC代码:
#include <bits/stdc++.h>
using namespace std;
int dp[102][102];
int sum[102];
int a[102];
int n;
int solve(int l, int r){
if(dp[l][r] != -1) return dp[l][r];
if(l > r) return dp[l][r] = 0;
int Sum = sum[r] - sum[l-1];
int ans = -123456789;
for(int k=1; k<=r-l+1; k++) //枚举选取个数
ans = max(ans, Sum - min(solve(l+k, r), solve(l, r-k)));
return dp[l][r] = ans;
}
int main(){
#ifdef sxk
freopen("in.txt", "r", stdin);
#endif // sxk
while(scanf("%d", &n) == 1 && n){
sum[0] = 0;
for(int i=1; i<=n; i++){
scanf("%d", &a[i]);
sum[i] = sum[i-1] + a[i];
}
memset(dp, -1, sizeof(dp));
printf("%d\n", solve(1, n) - (sum[n] - sum[0] - solve(1, n)));
}
return 0;
}