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





 

你可能感兴趣的:(DP,博弈论)