hdu 5795 A Simple Nim(SG打表找规律)

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.

思路:打个sg[]表找下规律,打表后发现当x%8==0 sg[x]=x-1,当x%8==7 sg[x]=x+1,其他的sg[x]=x

代码如下

#include  
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std; 
#define ll long long int 
/*
dfs打表
*/
//int sg[10006];
//int getsg(int x)
//{
//  if(sg[x]!=-1) return sg[x];
//  if(x==0) return 0;
//  if(x==1) return 1;
//  
//  int vis[10006];
//  memset(vis,0,sizeof(vis));
//  
//  for(int i=0;i
//  vis[getsg(i)]=1;
//  
//  for(int i=1;i
//      for(int j=i;j
//          for(int k=j;k
//              if(i+j+k==x)
//              vis[getsg(i)^getsg(j)^getsg(k)]=1;
//              
//      for(int i=0;;i++)
//      {
//        if(vis[i]==0){
//            return i;
//        }
//    }
//}
int main()  
{    
//  memset(sg,-1,sizeof(sg));
//  for(int i=1;i<100;i++)
//  {
//      sg[i]=getsg(i);
//      cout<
//  }
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int sum=0;
        int n;
        scanf("%d",&n);
        while(n--)
        {
            int x;
            scanf("%d",&x);
            if(x%8==0) sum^=(x-1);
            else if(x%8==7) sum^=(x+1);
            else 
            sum^=x;
        }
        if(sum) 
            printf("First player wins.\n");
        else 
            printf("Second player wins.\n");
    }
    return 0;  
}  

不用dfs,直接打表代码

#include  
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std; 
#define ll long long int 

int sg[10006];
int vis[10006];


void get_sg()
{
    sg[0]=0;
    sg[1]=1;
    sg[2]=2;

    for(int i=3; i <=10006; i++)
    {
        memset(vis, 0, sizeof(vis));

        for(int j=0;j1;

        for(int j = 1; j <= i / 3; j++)
            for(int k = 1; k <= i / 3; k++)
                vis[sg[j]^sg[i-j-k]^sg[k]] = 1;

        for(int j=0;;j++)
        {
            if(!vis[j])
            {
                sg[i]=j;
                break;
            }
        }
    }
    return ;
}
int main()  
{    
    get_sg();

    for(int i=1;i<=100;i++)
    cout<' '<

你可能感兴趣的:(博弈论)