UVA 10891 Game of Sum (博弈论 + 区间dp)

10 篇文章 0 订阅
10 篇文章 1 订阅

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值