Game of Sum UVA - 10891 Sum游戏 区间dp

 题目链接

     This is a two player game. Initially there are n integer numbers in an array and players A and B get chance to take them alternatively. Each player can take one or more numbers from the left or right end of the array but cannot take from both ends at a time. He can take as many consecutive numbers as he wants during his time. The game ends when all numbers are taken from the array by the players. The point of each player is calculated by the summation of the numbers, which he has taken. Each player tries to achieve more points from other. If both players play optimally and player A starts the game then how much more point can player A get than player B? 

 分析:用d(i,j) 表示i~j序列之间双方都采取最优策略下,先手能得到的最大值,则:d(i,j)等于sum(i,j)-下一位所有可能的最小值(向左,向右枚举,注意有可能不能选取,上一位已经选完)

d(i,j) = sum(i,j) - min(d(i+1,j)...d(j,j),d(i,j-1)...d(i,i),0)

方法一:直接枚举,O(n^3).

#include <cstdio>
#include <cstring> 
#include <algorithm>
using namespace std;

const int N = 100+5;
int num[N], sum[N], d[N][N]; // d(i,j)表示能在i,j中取得的最大值 
bool vis[N][N];

int dp(int i,int j){
	if(vis[i][j])  return d[i][j];
	vis[i][j] = true;
	int ans = 0; // 已经被取光,什么也不能选 
	for(int k = i; k < j; k++) //从左往右取 
		ans = min(ans, dp(i,k));  
	for(int k = j; k > i; k--) //从右往左取
		ans = min(ans, dp(k,j)); 
	return d[i][j] = sum[j] - sum[i-1] - ans;
}

int main(int argc, char** argv) {
	int n;
	while( ~scanf("%d",&n) && n){
		for(int i = 1; i <= n; i++)
			scanf("%d",&num[i]);
		for(int i = 1; i <= n; i++)
			sum[i] = sum[i-1]+num[i];
		memset(vis, 0, sizeof(vis));
		printf("%d\n", 2*dp(1,n) - sum[n]);
	} 
	return 0;
}

方法二:递推

f(i,j) = min\begin{Bmatrix} d(i,j),d(i,j+1)...d(j,j) \end{Bmatrix},g(i,j) = min\begin{Bmatrix} d(i,j),d(i,j-i)...d(i,i) \end{Bmatrix},

d(i,j) = sum(i,j) - min\begin{Bmatrix} f(i+1,j),g(i,j-1),0 \end{Bmatrix},时间复杂度O(n*n)

#include <cstdio>
#include <cstring> 
#include <algorithm>
using namespace std;

const int N = 100+5;
int num[N], sum[N], d[N][N], f[N][N], g[N][N]; 

int main(int argc, char** argv) {
	int n;
	while( ~scanf("%d",&n) && n){
		for(int i = 1; i <= n; i++)
			scanf("%d",&num[i]);
		for(int i = 1; i <= n; i++)
			sum[i] = sum[i-1]+num[i];
		for(int i = 1; i <= n; i++) // border
			f[i][i] = g[i][i] = d[i][i] = num[i];
		for(int len = 1; len < n; len++){ //按照len=j-i递增的顺序计算 
			for(int i = 1; i+len <= n; i++){
				int j = i + len;
				int m = 0;
				m = min(m, f[i+1][j]);
				m = min(m, g[i][j-1]);
				d[i][j] = sum[j] - sum[i-1] - m;
				f[i][j] = min(d[i][j], f[i+1][j]); //递推f和g 
				g[i][j] = min(d[i][j], g[i][j-1]);  
			}
		}	
		printf("%d\n", 2*d[1][n] - sum[n]);
	} 
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值