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
1≤T≤100
, 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[n−1]
, representing heaps with
s[0],s[1],...,s[n−1]
objects respectively.
(1≤n≤10
6
,1≤s[i]≤10
9
)
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
题意:有
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;
}