Nim or not Nim?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 997 Accepted Submission(s): 488
Nim is usually played as a misere game, in which the player to take the last object loses. Nim can also be played as a normal play game, which means that the person who makes the last move (i.e., who takes the last object) wins. This is called normal play because most games follow this convention, even though Nim usually does not.
Alice and Bob is tired of playing Nim under the standard rule, so they make a difference by also allowing the player to separate one of the heaps into two smaller ones. That is, each turn the player may either remove any number of objects from a heap or separate a heap into two smaller ones, and the one who takes the last object wins.
2 3 2 2 3 2 3 3
Alice Bob
g(x) = mex ( sg(y) |y是x的后继结点 )
其中mex(x)(x是一个自然是集合)函数是x关于自然数集合的补集中的最小值,比如x={0,1,2,4,6} 则mex(x)=3;
什么是后继结点?
所谓后继结点就是当前结点经过一个操作可以变成的状态。比如对于娶4石子游戏,假如每次可以取的数目是1,2,4,当前的石子数目也就是当前状态是5,那么5的后继结点就是{5-1, 5-2, 5-4}={4,3,1};
如果5的三个后继结点的SG函数值分别为0,1,3,那么5的SG值就是集合{0,1,3}的补集的最小元素,也就是2。
关于整个游戏的sg值之和sum,定义sum=sg1 ^ sg2 ^ sg3 ^ ……sgn. 其中^表示按位异或运算。
结论:一个游戏的初始局面是必败态当且仅当sum=0。
分析:很明显:sg(0) = 0,sg(1) = 1。
状态2的后继有:0,1和(1,1),他们的SG值分别为0,1,0,所以sg(2) =2。
状态3的后继有:0、1、2、(1,2),他们的SG值分别为0、1、2、3,所以sg(3) = 4。
状态4的后继有:0、1、2、3、(1,3)和(2,2),他们的SG值分别为0,1,2,4,5,0,所以sg(4) = 3.
再推一些,推测得到:对于所有的k >= 0,有 sg( 4k+1 ) = 4k+1; sg( 4k+2 ) = 4k+2; sg( 4k+3 ) = 4k+4; sg( 4k+4 ) = 4k+3。
也可以通过打表来找规律,打表代码#include<iostream>
#include<string.h>
#define N 1000001
using namespace std;
int sg[N];
int g(int x)
{
int mex[1000];
memset(mex,0,sizeof(mex));
if(sg[x]!=-1) return sg[x];
for(int i=x-1;i>=0;i--)
{
mex[g(i)]=1;
}
for(int i=1;i<=x/2;i++)
{
int ans=0;
ans^=g(i);
ans^=g(x-i);
mex[ans]=1;
}
for(int i=0;;i++)
if(!mex[i]) return sg[x]=i;
}
int main()
{
int t , n ,x ;
scanf("%d",&t);
memset(sg,-1,sizeof(sg));
sg[0]=0;
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&x);
g(x); cout<<"sg[x]= "<<sg[x]<<endl;
}
for(int i=0;i<=100;i++)
{
cout<<sg[i]<<" ";
if(i%10==0) system("pause");
}cout<<endl;
}
return 0;
}
sg(4k)=4k-1;sg(4k+1)=4k+1;sg(4k+2)=4k+2;sg(4k+3)=4k+4;
ac代码
#include<stdio.h>
#include<string.h>
int main()
{
int t,n,x,i;
int ans;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
ans=0;
for(i=0;i<n;i++)
{
scanf("%d",&x);
if(x%4==0)
ans^=(x-1);
else
if(x%4==1)
ans^=x;
else
if(x%4==2)
ans^=x;
else
ans^=(x+1);
}
if(ans!=0) printf("Alice\n");
else printf("Bob\n");
}
}