標籤:dfs
轉載請註明出處:http://blog.csdn.net/u012860063題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=4597題意 Alice和Bob玩一個遊戲,有兩個長度為N的正整數數字序列,每次他們兩個
只能從其中一個序列,選擇兩端中的一個拿走。他們都希望可以拿到盡量大
的數字之和,並且他們都足夠聰明,每次都選擇最優策略。Alice先選擇,問
最終Alice拿到的數字總和是多少?
Problem DescriptionAlice 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?InputThe 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).OutputFor 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
Source2013 ACM-ICPC吉林通化全國邀請賽——題目重現
代碼如下:
#include <cstdio>#include <cstring>#define MAX 20+10int s1[MAX], s2[MAX], sum1[MAX], sum2[MAX];int dp[MAX][MAX][MAX][MAX];//dp[a][b][i][j]表示當前玩家從s1的a~b,s2的i~j能獲得的最大價值 int max(int a, int b){if(a > b)return a;return b;}int dfs(int a, int b, int i, int j){if(dp[a][b][i][j])return dp[a][b][i][j];if(a > b && i > j)return 0;int max1 = 0;int max2 = 0;if(a <= b)max1=max(s1[a]+dfs(a+1,b,i,j),s1[b]+dfs(a,b-1,i,j));//取前後中值大的if(i <= j)max2=max(s2[i]+dfs(a,b,i+1,j),s2[j]+dfs(a,b,i,j-1));//取前後中值大的dp[a][b][i][j]=sum1[b]-sum1[a-1]+sum2[j]-sum2[i-1]-max(max1,max2);//區間和減去對手所取的剩下的就為當前玩家的return dp[a][b][i][j];}int main(){int t, n;while(~scanf("%d",&t)){while(t--){memset(dp,0,sizeof(dp));memset(sum1,0,sizeof(sum1));memset(sum2,0,sizeof(sum2));int ans = 0;int i, j;scanf("%d",&n);for(i = 1; i <= n; i++){scanf("%d",&s1[i]);sum1[i] = sum1[i-1]+s1[i];}for(i = 1; i <= n ; i++){scanf("%d",&s2[i]);sum2[i] = sum2[i-1]+s2[i];}ans = sum1[n]+sum2[n]-dfs(1,n,1,n);printf("%d\n",ans);}}return 0;}