1. 程式人生 > >2013 ACM-ICPC吉林通化全國邀請賽 && HDU 4597 Play Game (博弈 + 區間dp)

2013 ACM-ICPC吉林通化全國邀請賽 && HDU 4597 Play Game (博弈 + 區間dp)

Play Game

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 1185 Accepted Submission(s): 685


Problem Description
Alice and Bob are playing a game. There are two piles of cards. There are N cards in each pile, and each card has a score. They take turns to pick up the top or bottom card from either pile, and the score of the card will be added to his total score. Alice and Bob are both clever enough, and will pick up cards to get as many scores as possible. Do you know how many scores can Alice get if he picks up first?


Input
The first line contains an integer T (T≤100), indicating the number of cases.
Each case contains 3 lines. The first line is the N (N≤20). The second line contains N integer ai (1≤ai≤10000). The third line contains N integer bi (1≤bi≤10000).


Output
For each case, output an integer, indicating the most score Alice can get.


Sample Input
2

1
23
53

3
10 100 20
2 4 3


Sample Output
53
105


Source

2013 ACM-ICPC吉林通化全國邀請賽——題目重現


Recommend
liuyiding

解析:dp[l1][r1][l2][r2]代表第一段剩下l1~r1可以取,第二段還剩下l2~r2可以取的時候,能夠取到的最大值

sum1[i]代表第一段從開頭到當前位置的和

sum2[i]代表第二段從開頭到當前位置的和

每次取都有四種情況:

 從第一行最左端取

 從第一行最右端取

 從第二行最左端取

 從第二行最右端取

因此,dp[l1][r1][l2][r2]就由

 dp[l1+1][r1][l2][r2]

 dp[l1][r1-1][l2][r2]

 dp[l1][r1][l2+1][r2]

 dp[l1][r1][l2][r2-1]

轉移而來

針對當前是Alice取,則上一次則是Bob取,因為l1~r1和l2~r2區間的總分數sum1[r1] - sum1[l1-1] + sum2[r2] - sum2[l2-1]是固定的,欲使Alice取得最大的,則Alice要選取上次Bob的最小選擇進行狀態轉移

即  dp[l1][r1][l2][r2] = (sum1[r1] - sum1[l1-1] + sum2[r2] - sum2[l2-1]) - min{dp[l1+1][r1][l2][r2], dp[l1][r1-1][l2][r2], dp[l1][r1][l2+1][r2], dp[l1][r1][l2][r2-1]} 再加個記憶化,會省點時間 AC程式碼:
#include <bits/stdc++.h>
using namespace std;

int dp[22][22][22][22];
int sum1[22], sum2[22];
int a[22], b[22];
int n;

int solve(int l1, int r1, int l2, int r2){
    if(dp[l1][r1][l2][r2] != -1) return dp[l1][r1][l2][r2];
    if(l1 > r1 && l2 > r2) return dp[l1][r1][l2][r2] = 0;
    int sum = 0;
    int ans = 0;
    if(l1 <= r1) sum += sum1[r1] - sum1[l1-1];
    if(l2 <= r2) sum += sum2[r2] - sum2[l2-1];
    if(l1 <= r1) ans = max(ans, sum - min(solve(l1+1, r1, l2, r2), solve(l1, r1-1, l2, r2)));
    if(l2 <= r2) ans = max(ans, sum - min(solve(l1, r1, l2+1, r2), solve(l1, r1, l2, r2-1)));
    return dp[l1][r1][l2][r2] = ans;
}

int main(){
    #ifdef sxk
        freopen("in.txt", "r", stdin);
    #endif // sxk
    int t;
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        sum1[0] = sum2[0] = 0;
        for(int i=1; i<=n; i++){
            scanf("%d", &a[i]);
            sum1[i] = sum1[i-1] + a[i];
        }
        for(int i=1; i<=n; i++){
            scanf("%d", &b[i]);
            sum2[i] = sum2[i-1] + b[i];
        }
        memset(dp, -1, sizeof(dp));
        printf("%d\n", solve(1, n, 1, n));
    }
    return 0;
}