黑板异或游戏
给 n n n个非负数,两个人轮流玩游戏,如果玩家擦出一个数后,剩下的数字异或为0,则该玩家输,也就是说当前玩家黑板上的数字异或为0,则该玩家赢,比如1,2,3,先手赢。
1 ≤ n ≤ 1 0 6 1 \leq n \leq 10^6 1≤n≤106
题解
注意到:一个玩家面临的初始数字个数是奇数(偶数)个的话,那么一直到游戏结束,他面临的数字个数仍然是奇数(偶数)个。 故从奇偶性角度考虑。假设先手面临的数字是偶数个,记 a 1 ⊕ a 2 ⊕ ⋯ ⊕ a n = S a_1 \oplus a_2 \oplus \cdots \oplus a_n = S a1⊕a2⊕⋯⊕an=S;如果 S = 0 S = 0 S=0,先手赢;如果 S ≠ 0 S \neq 0 S=0,考虑先手在什么情况下必输?只有当任意擦除一个数后,剩下的数字异或为0,即擦除任意一个数 a i a_i ai,都有:
a 1 ⊕ a 2 ⊕ ⋯ ⊕ a i − 1 ⊕ a i + 1 ⋯ ⊕ a n = 0 a_1 \oplus a_2 \oplus \cdots \oplus a_{i - 1} \oplus a_{i + 1} \cdots \oplus a_n = 0 a1⊕a2⊕⋯⊕ai−1⊕ai+1⋯⊕an=0用 S S S表示: S ⊕ a i = 0 S \oplus a_i = 0 S⊕ai=0。进一步有:
( S ⊕ a 1 ) ⊕ ( S ⊕ a 2 ) ⊕ ( S ⊕ a 3 ) ⋯ ⊕ ( S ⊕ a n ) = 0 (1) (S \oplus a_1) \oplus (S \oplus a_2) \oplus (S \oplus a_3) \cdots \oplus (S \oplus a_n) = 0 \tag{1} (S⊕a1)⊕(S⊕a2)⊕(S⊕a3)⋯⊕(S⊕an)=0(1)而
( S ⊕ a 1 ) ⊕ ( S ⊕ a 2 ) ⊕ ( S ⊕ a 3 ) ⋯ ⊕ ( S ⊕ a n ) = ( S ⊕ S ⊕ ⋯ ⊕ S ) ⊕ ( a 1 ⊕ a 2 ⊕ ⋯ ⊕ a n ) = S (2) (S \oplus a_1) \oplus (S \oplus a_2) \oplus (S \oplus a_3) \cdots \oplus (S \oplus a_n) = (S \oplus S \oplus \cdots \oplus S) \oplus (a_1 \oplus a_2 \oplus \cdots \oplus a_n) = S \tag{2} (S⊕a1)⊕(S⊕a2)⊕