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

版权声明:本文为博主原创文章,未经博主允许不得转载,欢迎添加友链。 https://blog.csdn.net/qq_42835910/article/details/90072745

 题目链接

     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;
}

猜你喜欢

转载自blog.csdn.net/qq_42835910/article/details/90072745