博弈——Playing With Stones(SG 打表找规律)
题目链接:
UVA - 1482
You and your friend are playing a game in which you and your friend take turns removing stones from
piles. Initially there are N piles with a1, a2, a3, . . . , aN number of stones. On each turn, a player must
remove at least one stone from one pile but no more than half of the number of stones in that pile.
The player who cannot make any moves is considered lost. For example, if there are three piles with
5, 1 and 2 stones, then the player can take 1 or 2 stones from first pile, no stone from second pile, and
only 1 stone from third pile. Note that the player cannot take any stones from the second pile as 1 is
more than half of 1 (the size of that pile). Assume that you and your friend play optimally and you
play first, determine whether you have a winning move. You are said to have a winning move if after
making that move, you can eventually win no matter what your friend does.
Input
The first line of input contains an integer T (T ≤ 100) denoting the number of testcases. Each testcase
begins with an integer N (1 ≤ N ≤ 100) the number of piles. The next line contains N integers
a1, a2, a3, . . . , aN (1 ≤ ai ≤ 2 ∗ 1018) the number of stones in each pile.
Output
For each testcase, print ‘YES’ (without quote) if you have a winning move, or ‘NO’ (without quote) if
you don’t have a winning move.
Sample Input
4
2
4 4
3
1 2 3
3
2 4 6
3
1 2 1
Sample Output
NO
YES
NO
YES
题目大意
有 n 堆石子,分别有 a1,a2,…,an 个。每个人每次可以选择一堆拿石子,每次最少拿走一个石子,最多不能超过一半,两人轮流拿,不能拿的人就输了。
分析
可以通过 SG 打表找出规律:
1.当 n 为偶数时,SG(n) = n/2
2.当 n 为奇数时,SG(n) = SG(n/2)
打表代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int S[100000],SG[100000];
void getSG(int n)
{
memset(SG,0,sizeof(SG));
for(int i=1;i<=n;i++){
memset(S,0,sizeof(S));
for(int j=1;j<=i/2;j++){
S[SG[i-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<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
typedef long long ll;
using namespace std;
ll SG(ll n)
{
if(n%2==0){
return n/2;
}
else{
return SG(n/2);
}
}
int main()
{
ll t,n;
cin>>t;
while(t--){
cin>>n;
ll ans=0;
for(ll i=0;i<n;i++){
ll x;
cin>>x;
ans^=SG(x);
}
if(ans){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
return 0;
}