题目摘自常用代码模板4——数学知识 - AcWing
https://www.acwing.com/blog/content/406/
一、NIM博弈
#include<iostream>
using namespace std;
const int N=100010;
int a[N];
int main(){
int n;
cin >> n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int flag=0;
for(int i=1;i<=n;i++){
flag^=a[i];
}
if(flag==0)cout<<"No";
else cout <<"Yes";
return 0;
}
巧妙利用按位异或得出结论。
二、SG函数
#include<iostream>
#include<algorithm>
#include<cstring>
#include<unordered_set>
using namespace std;
const int N = 110, M = 10010;
int n, m;
int s[N], f[M];
int sg(int x)
{
if(f[x]!=-1) return f[x];
//因为取石子数目的集合是已经确定了的,所以每个数的sg值也都是确定的,如果存储过了,直接返回即可
unordered_set<int> S;
//(注:因为在函数内部定义,所以下一次递归中的S不与本次相同)
for(int i=0;i<m;i++)
{
int sum=s[i];
if(x>=sum) S.insert(sg(x-sum));
//先延伸到终点的sg值后,再从后往前排查出所有数的sg值
}
for(int i=0;;i++)
//循环完之后可以进行选出最小的没有出现的自然数的操作
if(!S.count(i))
return f[x]=i;
}
int main()
{
cin >> m;
for (int i = 0; i < m; i ++ ) cin >> s[i];//s存入只能取哪些数
cin >> n;
memset(f, -1, sizeof f);//初始化f均为-1,方便在sg函数中查看x是否被记录过
int res = 0;
for (int i = 0; i < n; i ++ )
{
int x;
cin >> x;
res ^= sg(x);//对每一堆用NIM游戏的思想
}
if (res) puts("Yes");
else puts("No");
return 0;
}