博弈——Bash游戏 V3(SG 打表找规律)
题目链接:
51Nod - 1068
有一堆石子共有N个。A B两个人轮流拿,A先拿。每次拿的数量只能是2的正整数次幂,比如(1,2,4,8,16…),拿到最后1颗石子的人获胜。假设A B都非常聪明,拿石子的过程中不会出现失误。给出N,问最后谁能赢得比赛。
例如N = 3。A只能拿1颗或2颗,所以B可以拿到最后1颗石子。(输入的N可能为大数)
Input
第1行:一个数T,表示后面用作输入测试的数的数量。(1 <= T <= 1000) 第2 - T + 1行:每行1个数N。(1 <= N <= 10^1000)
Output
共T行,如果A获胜输出A,如果B获胜输出B。
Sample Input
3
2
3
4
Sample Output
A
B
A
分析
这题可以通过 SG 打表来寻找规律
从上图中可以看出,当 n % 3 = 0 时,B 赢,反之,A 赢。
打表代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int S[100000],SG[100000],f[10]={1,2,4,8,16,32,64,128,256,512};
void getSG(int n)
{
memset(SG,0,sizeof(SG));
for(int i=1;i<=n;i++){
memset(S,0,sizeof(S));
for(int j=0;j<10&&f[j]<=i;j++){
S[SG[i-f[j]]]=1;
}
for(int t=0; ;t++){
if(!S[t]){
SG[i]=t;
break;
}
}
cout<<"i="<<i<<" SG[i]="<<SG[i]<<endl;
}
}
int main()
{
getSG(100);
return 0;
}
AC 代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--){
string s;
cin>>s;
int n=0;
for(int i=0;i<s.length();i++){
n=(n+s[i]-'0')%3;
}
if(n==0){
cout<<"B"<<endl;
}
else{
cout<<"A"<<endl;
}
}
return 0;
}