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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章