24h購物| | PChome| 登入
2012-12-05 21:57:01| 人氣738| 回應0 | 上一篇 | 下一篇

[UVA][博奕][記憶化搜索] 10891 - Game of Sum

推薦 0 收藏 0 轉貼0 訂閱站台

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


Problem setter: Syed Monowar Hossain

Special Thanks: Derek Kisman, Mohammad Sajjad Hossain

看到博奕題目剛好會,立馬套用 INKER 模版,使用遞迴求解。

#include <stdio.h>
#define max(x, y) ((x) > (y) ? (x) : (y))
char done[101][101];
int dp[101][101], A[101];
int dfs(int l, int r) {
    if(l > r)      return 0;
    if(done[l][r])  return dp[l][r];
    int i, sum;
    dp[l][r] = -(1<<30);
    done[l][r] = 1;
    for(i = l, sum = 0; i <= r; i++) {
        sum += A[i];
        dp[l][r] = max(dp[l][r], sum-dfs(i+1, r));
    }
    for(i = r, sum = 0; i >= l; i--) {
        sum += A[i];
        dp[l][r] = max(dp[l][r], sum-dfs(l, i-1));
    }
    return dp[l][r];
}
int main() {
    int n, i, j;
    while(scanf("%d", &n) == 1 && n) {
        for(i = 0; i < n; i++)
            scanf("%d", A+i);
        for(i = 0; i <= n; i++)
            for(j = 0; j <= n; j++)
                done[i][j] = 0;
        printf("%d\n", dfs(0, n-1));
    }
    return 0;
}

台長: Morris
人氣(738) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][柯西不等式] 12575 - Sin Cos Problem
此分類上一篇:[UVA][日期計算][善用JAVA] 893 - Y3K Problem

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文