您的位置:首页 > 其它

HDU 5795 A Simple Nim(博弈)

2016-08-05 13:13 393 查看
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堆石子轮流操作,每一次可以选择从一堆石子中取走任意多个,或者把其中一堆石子数量大于等于三个的分成三份(每份数量随意)。取走最后一个石子的为赢家。

思路:sg[0]=0; sg[1]=1;sg[2]=2;sg[3]={0,1,2,(1,1,1)}=3;....

打表找规律,代码如下:

#include <iostream>
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <string.h>
#include <vector>
#include <queue>
#include <stack>
#include <ctype.h>
using namespace std;
const int N=1000010;

int sg
;

int g(int x){
int mex[1010];
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++)
{
for(int j=1;i+j<=x-1;j++)
{
int ans=0;
ans^=g(i);
ans^=g(j);
ans^=g(x-i-j);
mex[ans]=1;
}
}
for(int i=0;;i++)
if(!mex[i])
return sg[x]=i;
}

int main()
{
memset(sg,-1,sizeof(sg));
int x;
scanf("%d",&x);
for(int i=1;i<=x;i++)
{
g(i);
printf("sg[%d]=%d\n",i,sg[i]);
}
return 0;
}


发现规律为:sg[7]=8,sg[8]=7,sg[15]=16,sg[16]=15

sg[8k-1]=8k,sg[8k]=8k-1,其余的sg[i]=i。(sg[0]=0)

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <iostream>
#include <assert.h>

using namespace std;

int main()
{
int t,n;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
int ans=0,x;
for(int i=0;i<n;i++){
scanf("%d",&x);
if(x%8==0)
ans^=(x-1);
else if(x%8==7)
ans^=(x+1);
else
ans^=x;
}
if(ans!=0)
puts("First player wins.");
else
puts("Second player wins.");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: