HDU 5795 A Simple Nim(SG打表找规律)——2016 Multi-University Training Contest 6

来源:互联网 发布:新媒体沟通软件 编辑:程序博客网 时间:2024/04/30 22:02

传送门

A Simple Nim

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 55    Accepted Submission(s): 32


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 1T100, 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[n1], representing heaps with s[0],s[1],...,s[n1] objects respectively.(1n106,1s[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

题目大意:
T 组数据,然后有 n 堆石子,有两个人进行玩游戏,可以从一堆石子中取任意 x 个,也可以将一堆石子分成三堆,最后一个取到石子的赢。

解题思路:
这个题目首先,用 SG 打一个表找一下规律,然后打完表发现有一个规律,就是x MOD8 == 0x-1xMOD 8==7的时候 x+1 剩余情况不变,然后就异或和一下就行了。
My Code

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MAXN = 1e3+5;typedef long long LL;int sg[MAXN];int get_SG(int x){    if(sg[x]!=-1)        return sg[x];    int hash[MAXN];    memset(hash, 0, sizeof(hash));    for(int i=x-1; i>=0; i--)        hash[get_SG(i)]=1;    for(int j=1; j<=x; j++)    {        for(int jj=1; jj<=x; jj++)        {            if(x-j-jj > 0)                hash[get_SG(x-j-jj)^get_SG(j)^get_SG(jj)]=1;        }    }    int k;    for(k=0; k<MAXN; k++)    {        if(!hash[k])        {            return sg[x] = k;        }    }}int main(){    /**测试打表**/    /*memset(sg,-1,sizeof(sg));    for(int i=0; i<50; i++)    {        printf("sg[%d] = %d\n",i,get_SG(i));    }*/    int T;    cin>>T;    while(T--)    {        int m;        LL ans = 0;        cin>>m;        while(m--)        {            LL x;            cin>>x;            if(x%8==0)                ans ^= (x-1);            else if(x%8 == 7)                ans ^= (x+1);            else                ans ^= x;        }        if(ans)            puts("First player wins.");        else            puts("Second player wins.");    }    return 0;}
0 0
原创粉丝点击