A Simple Nim
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1906 Accepted Submission(s): 1002
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≤106,1≤s[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.
题意
有n堆糖果,每一次你可以选择一堆取走其中的任意个数糖果(不能不取)或者你将这一堆分成三小堆,谁先不能取谁输,现在问你谁能赢呢
思路
典型的nim博弈变形,套用sg函数模板
/f[]:可以取走的石子个数
//sg[]:0~n的SG函数值
//vis[]:mex{}
int f[N],sg[N],vis[N];
void getSG(int n)
{
memset(sg,0,sizeof(sg));
for(int i=1; i<=n; i++)
{
memset(vis,0,sizeof(vis));
for(int j=1;j<=i;j++)
vis[sg[j]]=1;//表示这一堆如果有i个,那么可以取1-i个糖果
for(int j=1; j<i-1; j++)//表示分成三堆的第一堆可以取1到i-2个
for(int k=1;k<i-j;k++)//若第一堆取了j个那么第二堆只能取1~i-j-1个
vis[sg[j]^sg[k]^sg[i-j-k]]=1;//分堆时vis中的值为可以分成的堆的数量的异或值
for(int j=0; j<=n; j++)
{
if(vis[j]==0)
{
sg[i]=j;
break;
}
}
}
}
然后打表发现
1 1
2 2
3 3
4 4
5 5
6 6
7 8
8 7
9 9
10 10
11 11
12 12
13 13
14 14
15 16
16 15
17 17
18 18
19 19
20 20
21 21
22 22
23 24
24 23
25 25
26 26
27 27
28 28
29 29
30 30
31 32
32 31
除了
x
%
8
=
=
0
x\%8==0
x%8==0是
x
−
1
x-1
x−1和
x
%
8
=
=
7
x\%8==7
x%8==7是
x
+
1
x+1
x+1之外其他的x都是x自己
那么直接异或和判断就可以了
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int sum=0;
for(int i=0;i<n;i++)
{
int x;
scanf("%d",&x);
if(x%8==7)
x=x+1;
else if(x%8==0)
x=x-1;
sum^=x;
}
if(sum==0)
{
printf("Second player wins.\n");
}
else
printf("First player wins.\n");
}
return 0;
}