HDU 5795 A Simple Nim (SG博弈)

A Simple Nim

Problem Description
Two players take turns picking candies from n heaps,the player who picks the last one will win the game.On each turn they can pick any number of candies which come from the same heap(picking no candy is not allowed).To make the game more interesting,players can separate one heap into three smaller heaps(no empty heaps)instead of the picking operation.Please find out which player will win the game if each of them never make mistakes.
Input
Intput contains multiple test cases. The first line is an integer 1T100 , the number of test cases. Each case begins with an integer n, indicating the number of the heaps, the next line contains N integers s[0],s[1],....,s[n1] , representing heaps with s[0],s[1],...,s[n1] objects respectively. (1n106,1s[i]109)
Output
For each test case,output a line whick contains either"First player wins."or"Second player wins".
Sample Input
  
  
2 2 4 4 3 1 2 4
Sample Output
  
  
Second player wins. First player wins.
Author
UESTC
Source
Recommend
wange2014   |   We have carefully selected several similar problems for you:  5803 5802 5801 5800 5799 

题意:有 n堆的取石子游戏,规定每次可以取一堆中的任意个,或者将当前堆分为三个非空堆。最后一个取石子的胜。求先手胜还是后手必胜。
题解: 打表找规律。
sg[0]=0;

当k%8==7时sg[x]=k+1,

当k%8==0时sg[x]=k-1 ,

其余时候:sg[x]=x;(k>=0)


打表代码:

#include<bits/stdc++.h>
int g[100];
int f[100];
void Da_Biao(int n)
{
    memset(f,false,sizeof(f));
    for(int i=0;i<n;i++)
    {
		f[g[i]]=1;
	}

    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            for(int k=1;k<=n;k++)
            {
                if((i+j+k)==n)
                {
                    f[(g[i]^g[j]^g[k])]=1;
                }
            }
        }
    }
    int i;
    for(i=0;;i++)
    {
        if(f[i]==0){
			break; 
		}
    }
    g[n]=i;
    printf("i=%d sg[%d]=%d\n",n,n,i);
    
}
int main()
{
     g[0]= 0;
     memset(g,0,sizeof(g));
     for(int i=1;i<=40;i++)
     {
         Da_Biao(i);
     }

    return 0;
}


AC代码:

#include<bits/stdc++.h>
using namespace std;
int SG(int x)
{
	if(x%8==0)return x-1;
	if(x%8==7)return x+1;
	return x;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		int ans=0;
		int a=0;
		for(int i=0;i<n;i++)
		{
			scanf("%d",&a);
			ans ^= SG(a);
		}
		if(!ans)puts("Second player wins.");
		else puts("First player wins.");
    }
	return 0;
}


  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值