题意:A和B玩一个游戏,有两组卡片,每张卡片有一个点数,两人轮流从任意一组的最左端或者最右端取一张,两人都足够聪明。选取一种最优的方案,使得A获得的点数和最高。
链接:http://acm.hdu.edu.cn/showproblem.php?pid=4597
思路:区间DP(记忆化搜索),取的方式从两种变成四种,状态转移方程为 ans = max ( ans, sum-dfs(a-1, b,c, d), sum-dfs(a,b-1,c,d),sum-dfs(a,b,c-1,d),sum-dfs(a,b,c,d-1))
注意点:注意边界问题,开始没考虑到边界,参考了bin神的代码,发现边界问题,然后A了。
以下为AC代码:
Run ID | Submit Time | Judge Status | Pro.ID | Exe.Time | Exe.Memory | Code Len. | Language | Author |
12433404 | 2014-12-08 21:07:22 | Accepted | 4597 | 109MS | 4348K | 2073 B | G++ | luminous11 |
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <deque>
#include <list>
#include <cctype>
#include <algorithm>
#include <climits>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#define ll long long
#define ull unsigned long long
#define all(x) (x).begin(), (x).end()
#define clr(a, v) memset( a , v , sizeof(a) )
#define pb push_back
#define mp make_pair
#define read(f) freopen(f, "r", stdin)
#define write(f) freopen(f, "w", stdout)
using namespace std;
int num1[30];
int num2[30];
int sum1[30];
int sum2[30];
int dp[30][30][30][30];
int sum = 0;
struct node
{
int a;
int b;
}cnt[2];
int dfs( int a, int b, int c, int d )
{
int sum = 0;
int ans = 0;
if ( dp[a][b][c][d] != -1 )
return dp[a][b][c][d];
if ( a > b && c > d )
return dp[a][b][c][d] = 0;
if ( a <= b )
{
sum += sum1[b] - sum1[a-1];
}
if ( c <= d )
{
sum += sum2[d] - sum2[c-1];
}
if ( a <= b )
{
ans = max ( ans, sum - dfs (a + 1, b, c, d ) );
ans = max ( ans, sum - dfs ( a, b - 1, c, d ) );
}
if ( c <= d )
{
ans = max ( ans, sum - dfs ( a, b, c + 1, d ) );
ans = max ( ans, sum - dfs ( a, b, c, d - 1 ) );
}
return dp[a][b][c][d] = ans;
}
int main()
{
ios::sync_with_stdio( false );
int t;
cin >> t;
while ( t -- )
{
int k;
cin >> k;
memset ( dp, -1, sizeof ( dp ) );
memset ( sum1, 0, sizeof ( sum1 ) );
memset ( sum2, 0, sizeof ( sum2 ) );
for ( int i = 1; i <= k; i ++ )
{
cin >> num1[i];
sum1[i] = sum1[i-1] + num1[i];
}
for ( int i = 1; i <= k; i ++ )
{
cin >> num2[i];
sum2[i] = sum2[i-1] + num2[i];
}
cout << dfs( 1, k, 1, k ) << endl;
}
return 0;
}