POJ 2311 Cutting Game (sg博弈)

这篇博客介绍了如何解决POJ 2311 Cutting Game问题,通过分析每张纸的SG值,揭示了SG值是其所有子状态异或和的性质,并指出每个子状态由两张纸构成,同样需要计算异或和。讨论了利用二维数组存储SG值的方法。

POJ 2311 Cutting Game

考虑每张纸的SG:

我们称当前纸可以切成的两张纸ai,bi为当前纸的子状态

那么当前纸的SG就是它所有子状态的异或和

而它的每一个子状态有2张纸,也是求异或和

因为每张纸的属性包括w和h,所以用到二维数组保存sg值(当然结构体保存一张纸的属性也可)

#define mem(a,x) memset(a,x,sizeof(a))
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<set>
#include<stack>
#include<cmath>
#include<map>
#include<stdlib.h>
#include<cctype>
#include<string>
using namespace std;
typedef long long ll;
const int N = 200;
int dp[N+5][N+5];
int SG(int w,int h)
{
    if (dp[w][h] != -1) return dp[w][h];
    set<int>s;
    for (int i = 2;w - i>= 2;++i) s.insert(SG(i,h)^SG(w-i,h));
    for (int i = 2;h - i>= 2;++i) s.insert(SG(w,i)^SG(w,h-i));
    int res = 0;
    while (s.count(res)) res++;//找到不在集合中的最小的非负整数
    return dp[w][h] = res;
}
int main()
{
    int w,h;mem(dp,-1);
    while (~scanf("%d %d",&w,&h))
    {
        if (SG(w,h)) puts("WIN");
        else puts("LOSE");
    }
    return 0;
}

java:

//package acm.poj2311;
import java.util.*;
//博弈
public class Main {
	final static int N = 204;
	static int sg[][] = new int [N][N];
	static int SG(int w,int h){
		if (sg[w][h]!=-1) return sg[w][h];
		boolean vis[] = new boolean [N];
		for (int i = 2;w-i >= 2;++i) {
			vis[SG(i,h)^SG(w-i,h)] = true;//横着切分成i和w-i
		}
		for (int i = 2;h-i >= 2;++i){
			vis[SG(w,i)^SG(w,h-i)] = true;//竖着切分成i和h-i
		}
		int g = 0;
		while (vis[g]) ++g;
		return sg[w][h] = g;
	}
	static void init(){
		for (int i = 0;i < N;++i){
			Arrays.fill(sg[i], -1);
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		@SuppressWarnings("resource")
		Scanner in = new Scanner(System.in);
		init();
		while (in.hasNext()){
			int w = in.nextInt();
			int h = in.nextInt();
			if (SG(w,h)!=0) System.out.println("WIN");
			else System.out.println("LOSE");
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值