Nim - sg函数

#include
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
 
using namespace std;
 
typedef pair PII;
typedef long long ll;
typedef long double ld;

const int N = 110, M = 10010;

int n, k;
int s[N], f[M];

int sg(int x)
{
    if(f[x] != -1)return f[x];

    unordered_set S;
    for(int i = 1; i <= k; i ++)
    {
        if(x >= s[i])S.insert(sg(x - s[i]));
    }
    for(int i = 0; ; i ++)
    {
        if(!S.count(i))
        {
            return f[x] = i;
        }
    }
}

int main()
{
	IOS
	cin >> k;
	for(int i = 1; i <= k; i ++)cin >> s[i];
	
	memset(f, -1, sizeof f);
	int res = 0;
	cin >> n;
	for(int i = 0; i < n; i ++)
	{
		int x;
		cin >> x;
		res ^= sg(x);
	}
	
	if(res)cout << "Yes";
	else cout << "No";
	
	return 0;
}

sg(a1)^sg(a2)^...^sg(an) != 0必胜,等于零必败

你可能感兴趣的:(模板,c++,算法)