A Simple Nim
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1132 Accepted Submission(s): 638
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.
Author
UESTC
Source
解题:
先小数据打表求sg值,可以发现sg值的规律。当i%8==7时,其sg值为i+1,当i%8==0时,其sg值为i-1(sg[0]=0)。一个状态的sg值,是其后继状态sg值中未出现过最小整数,三堆的sg值是三堆石子数量sg值的异或。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
#define ll long long
#define ms(a,b) memset(a,b,sizeof(a))
const int M=1e3+10;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
int i,j,k,n,m;
int sg[100];
int vis[100];
void solve()
{
int tmp;
sg[0]=0;
for(int i=1;i<40;i++){
ms(vis,0);
for(int j=0;j<i;j++){
vis[sg[j]]=1;
for(int k=1;k<i;k++)
for(int m=1;m<i;m++){
int u=i-k-m;
if(u>0){
tmp=sg[u]^sg[k]^sg[m];
vis[tmp]=1;
}
else break;
}
}
for(int x=0;;x++){
if(!vis[x]){
sg[i]=x;
printf("%d\n",x);
break;
}
}
}
}
int main()
{
//solve();
int t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
int ans=0;
for(int i=1;i<=n;i++){
int a;
scanf("%d",&a);
if(a%8==0)a--;
else if(a%8==7)a++;
ans^=a;
}
if(!ans)printf("Second player wins.\n");
else printf("First player wins.\n");
}
return 0;
}