51 nod1067 Bash游戏 V2(sg函数打表)

1067 Bash游戏 V2

 

有一堆石子共有N个。A B两个人轮流拿,A先拿。每次只能拿1,3,4颗,拿到最后1颗石子的人获胜。假设A B都非常聪明,拿石子的过程中不会出现失误。给出N,问最后谁能赢得比赛。

例如N = 2。A只能拿1颗,所以B可以拿到最后1颗石子。

 

输入

第1行:一个数T,表示后面用作输入测试的数的数量。(1 <= T <= 10000)
第2 - T + 1行:每行1个数N。(1 <= N <= 10^9)

输出

共T行,如果A获胜输出A,如果B获胜输出B。

sg函数先打表,然后找规律。我们可以发现当n%7==0||n%7==2时sg值为0。
打表代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=100,M=5e5+5;
int v[N],sg[N],s[3]={1,3,4};
int mex(int x)
{
    memset(v,0,sizeof(v));
    for(int i=0;i<3;i++)
    {
        if(x<s[i])
            break;
        v[sg[x-s[i]]]=1;
    }
    for(int i=0;;i++)
    {
        if(!v[i])
            return i;
    }
}
int main()
{
    int i;
    sg[0]=0;
    for(int i=1;i<N;i++)
    {
        sg[i]=mex(i);
    }
    for(int i=0;i<N;i++)
    {
        printf("sg[%d] = %d
",i,sg[i]);
    }
    return 0;
}

AC代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long

int main()
{
    int T,n,x;
    cin>>T;
    while(T--)
    {
        cin>>x;
        if(x%7==0||x%7==2)
        {
            printf("B
");
        }
        else
        {
            printf("A
");
        }
    }
   return 0;
}
原文地址:https://www.cnblogs.com/hh13579/p/11479898.html