博弈论
Nim博弈
结论:如果a0 ^ a1 ^ a2 ^ a3 ^ … ^ an = 0先手必败。
否则先手必胜。
证明:
假设:a0 ^ a1 ^ … ^ an = x;
x的二进制表示中最高一位1在第k位,那么a1~an中必然存在一个数ai在第k位也为1。由于ai ^ x < ai,所以拿走ai - (ai - ai ^ x)个石子,剩下ai ^ x个石子。
a0 ^ a1 ^ … ^ ai ^ x ^ … ^ an = x ^ x = 0。
证得刚开始亦或值不为0的,一定可以转换成亦或值为0,所以先手第一步拿到的石子如果亦或值为0,必败,如果不为零,必胜。
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
const int N = 1e5 + 10, P = 131;
int main()
{
int n;
int res = 0;
cin >> n;
while(n --)
{
int x;
cin >> x;
res ^= x;
}
if(res) cout << "YES" << endl;
else cout << "NO" << endl;
}
SG函数
mex函数:找一个集合中不存在的最小的自然数。
在有向图游戏中,对于每个结点x,设从x触发共有k条有向边,分别到达节点y1,y2,…,yk的SG函数值构成的集合再执行mex(S)运算的结果。
SG(x) = mex({SG(y1), SG(y2), SG(y3), … ,SG(yk)})
整个有向图游戏G的SG函数值被定义为有向图起点s的SG函数值,即SG(G) = SG(s)。
有向图游戏的和:
设G1,G2,…,Gm是m个有向图游戏,设有向图G,它的行动规则是任选某个有向图游戏Gi,并在Gi上行动一步。
有向图游戏的和的SG函数值等于它包含的各个子游戏SG函数值的亦或和。
SG(G) = SG(G1) ^ SG(G2) ^ SG(G3) …SG(Gm)
定理:有向图的某个局面必胜,当且仅当该局面对应节点的SG函数值大于0。
有向图游戏的某个局面必败,当且仅当该局面对应节点的SG函数值等于0。
证明方法与Nim游戏相同。
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
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];
unordered_set<int> S;
for(int i = 0; i < m; i ++)
{
int sum = s[i];
if(x >= sum) S.insert(sg(x - sum));
}
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];
cin >> n;
memset(f, -1, sizeof f);
int res = 0;
for(int i = 0; i < n; i ++)
{
int x;
cin >> x;
res ^= sg(x);
}
if(res) cout << "YES" << endl;
else cout << "NO" << endl;
}