2013 ACM-ICPC吉林通化全国邀请赛——题目重现
http://acm.hdu.edu.cn/showproblem.php?pid=4597
题意
A,B玩游戏,有两个长度为N的正整数数字序列,每次他们只能从这两个序列的头尾,也就是四个数字中取走一个,问都选择最优策略的情况下,A先选择能得到的数字总和是多少?
思路
dfs(x , y , i , j)表示第一个序列剩下[x,y] ,第二个序列剩下[i , j]时,最多可以拿多少。
对于A,它当前的状态假设为dfs(x , y , i , j) 那么这个状态肯定是由四个状态转移过来,也就是dfs(x + 1, y , i , j)、dfs(x , y - 1, i , j),dfs(x , y , i + 1, j) 、dfs(x , y , i , j - 1)
A要做选择,肯定是要让B尽可能的少,所以我们选择这四个状态中最小的一个转移过来。而此时A获得的数字之和,就等于sum(x , y , i , j) - 上次B拿到的值。
也就是说
dfs(x, y , i , j)= sum(x , y , i , j) -
min{
dfs(x + 1, y , i , j),
dfs(x , y - 1, i , j),
dfs(x , y , i + 1, j) ,
dfs(x , y , i , j - 1)
}
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 40;
int a[maxn], b[maxn];
int sum_a[maxn], sum_b[maxn];
int ans[maxn][maxn][maxn][maxn];
int dfs(int pos1, int pos2, int pos3, int pos4, int sum)
{
int res = 0;
if(pos1 > pos2 && pos3 > pos4)
return 0;
if(ans[pos1][pos2][pos3][pos4])
return ans[pos1][pos2][pos3][pos4];
if(pos1 <= pos2)
{
res = max(res, sum - dfs(pos1 + 1, pos2, pos3, pos4, sum - a[pos1]));
res = max(res, sum - dfs(pos1, pos2 - 1, pos3, pos4, sum - a[pos2]));
}
if(pos3 <= pos4)
{
res = max(res, sum - dfs(pos1, pos2, pos3 + 1, pos4, sum - b[pos3]));
res = max(res, sum - dfs(pos1, pos2, pos3, pos4 - 1, sum - b[pos4]));
}
ans[pos1][pos2][pos3][pos4] = res;
return res;
}
int main()
{
int T, n;
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
memset(ans, 0 ,sizeof(ans));
for(int i = 1; i <= n; i++) scanf("%d", &a[i]), sum_a[i] = sum_a[i - 1] + a[i];
for(int i = 1; i <= n; i++) scanf("%d", &b[i]), sum_b[i] = sum_b[i - 1] + b[i];
printf("%d\n", dfs(1, n, 1, n, sum_a[n] + sum_b[n]));
}
return 0;
}
参考来源
博客
https://blog.csdn.net/hit0803107/article/details/80960811