A Simple Nim
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/65536K (Java/Other)
Total Submission(s) : 5 Accepted Submission(s) : 3
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
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
Source
2016 Multi-University Training Contest 6
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
const int M = 100000;
using namespace std;
int vis[M], sg[M];
int get_sg(int n)
{
if(n % 8 == 0) {
return n-1;
} else if(n % 8 == 7) {
return n+1;
} else {
return n;
}
}
int main()
{
int T, n, i, j, sum, num[M];
scanf("%d", &T) ;
while(T--) {
scanf("%d", &n);
sum = 0;
for(i = 0; i < n; i++) {
scanf("%d", &num[i]);
sum ^= get_sg(num[i]);
}
if(!sum) {
printf("Second player wins.\n");
} else {
printf("First player wins.\n");
}
}
}
附上sg函数,自己可以输出sg函数找规律
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
const int M = 100000;
using namespace std;
int vis[100], sg[100];
void get_sg(int n) {
int i, j, k, sum;
memset(vis,0,sizeof(vis));
for(i = 0; i < n; i++) vis[sg[i]] = 1;
for(i = 1; i < n; i++) {
for(j = 1; j < n; j++) {
for(k = 1; k < n; k++) {
if(i + j + k == n) {
sum = (sg[j]^sg[i]^sg[k]);
vis[sum] = 1;
}
}
}
}
for(int i = 0; ; i++) {
if(!vis[i]) {
sg[n] = i;
break;
}
}
}
int main() {
memset(sg,0,sizeof(sg));
for(int i = 0; i < 50; i++) {
get_sg(i);
}
for(int i = 1; i < 50; i++) {
printf("%d %d\n", i,sg[i]);
}
return 0;
}
规律为:
当num%8==8 sg[ num ] = num-1;
当num%8==7 sg[ num ] = num+1;
其余sg[ num ] = num;