取走-分割 SG 函数

title: 题目
Alice和Bob轮流取N堆石子,每堆S[i]个,Alice先,每一次可以从任意一堆中拿走任意个石子,也可以将一堆石子分为两个小堆。先拿完者获胜。
 
title: input
2
3
2 2 3
2
3 3
title: output
Alice
Bob
 
title: 思路
每分割出去的部分是新的游戏,显然需要用到SG函数。
但跟[[#集合-sg函数|集合 SG函数]]的不一样, 无法通过枚举来打表, 需要找规律:
分割堆数用 `sg[j] ^ sg[i-j]`
~~~ c ++
int main()
{
 
    sg[0] = 0;
    sg[1] = 1;
    for (int i = 2; i <= N; i++)
    {
        bool st[N] = {};
        for (int j = 0; j <= i; j++)
        {
            st[sg[j]] = true;
            if (j && j != i)
                st[sg[j] ^ sg[i - j]] = true;
        }
        int j = 0;
        while (st[j])
            j++;
        sg[i] = j;
    }
    for (int i = 1; i <= 1000; i++)
    {
        cout << sg[i] << " ";
        if (i % 10 == 0)
            cout << endl;
    }
 
    return 0;
}
~~~
![[Pasted image 20220722163051.png]]
可以看出, 当 `n%4 == 0` 时, 会和 `n-1` 的数互换:
`sg[x] = x - 1(x%4 == 0)`
` sg[x] = x + 1(x%4==3)`
 
title:代码
~~~ c ++
#include <cstdio>
using namespace std;
int readInt()
{
	int t;
	scanf("%d", &t);
	return t;
}
int sg(int x)
{
    if (x % 4 == 0)
        return x - 1;
    else if (x % 4 == 3)
        return x + 1;
    else
        return x;
}
 
int main()
{
 
    int T = readInt();
    while (T--)
    {
        int n = readInt(), res = 0;
        while (n--)
            res ^= sg(readInt());
        if (res)
            printf("Alice\n");
        else
            printf("Bob\n");
    }
 
    return 0;
}
~~~