首页 > 代码库 > UVA - 10891 Game of Sum (区间dp)
UVA - 10891 Game of Sum (区间dp)
题意:AB两人分别拿一列n个数字,只能从左端或右端拿,不能同时从两端拿,可拿一个或多个,问在两人尽可能多拿的情况下,A最多比B多拿多少。
分析:
1、枚举先手拿的分界线,要么从左端拿,要么从右端拿,比较得最优解。
2、dp(i, j)---在区间(i, j)中A最多比B多拿多少。
3、tmp -= dfs(i + 1, r);//A拿了区间(l, i),B在剩下区间里尽可能拿最优
tmp是A拿的,dfs(i + 1, r)是B比A多拿的,假设dfs(i + 1, r)=y-x,y是B拿的,x是A拿的
则tmp-dfs(i + 1, r) = tmp - y + x,也就是最终A比B多拿的。
#include<cstdio>#include<cstring>#include<cstdlib>#include<cctype>#include<cmath>#include<iostream>#include<sstream>#include<iterator>#include<algorithm>#include<string>#include<vector>#include<set>#include<map>#include<stack>#include<deque>#include<queue>#include<list>#define lowbit(x) (x & (-x))const double eps = 1e-8;inline int dcmp(double a, double b){ if(fabs(a - b) < eps) return 0; return a > b ? 1 : -1;}typedef long long LL;typedef unsigned long long ULL;const int INT_INF = 0x3f3f3f3f;const int INT_M_INF = 0x7f7f7f7f;const LL LL_INF = 0x3f3f3f3f3f3f3f3f;const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};const int MOD = 1e9 + 7;const double pi = acos(-1.0);const int MAXN = 100 + 10;const int MAXT = 10000 + 10;using namespace std;int sum[MAXN];int dp[MAXN][MAXN];int dfs(int l, int r){ if(dp[l][r] != INT_INF) return dp[l][r]; int diff = sum[r] - sum[l - 1]; for(int i = l; i < r; ++i){//先手从左端拿 int tmp = sum[i] - sum[l - 1]; tmp -= dfs(i + 1, r);//后手从右端拿 if(tmp > diff) diff = tmp; } for(int i = l; i < r; ++i){ int tmp = sum[r] - sum[i]; tmp -= dfs(l, i); if(tmp > diff) diff = tmp; } return dp[l][r] = diff;}int main(){ int n; while(scanf("%d", &n) == 1){ if(!n) return 0; memset(dp, INT_INF, sizeof dp); sum[0] = 0; for(int i = 1; i <= n; ++i){ scanf("%d", &sum[i]); sum[i] += sum[i - 1]; } printf("%d\n", dfs(1, n)); } return 0;}
UVA - 10891 Game of Sum (区间dp)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。