跳到正文

题解

题解:P2197 【模板】nim 游戏

OldDriverTree约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年2月2日
更新
2026年3月2日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

更好的阅读体验

结论

先手必胜当且仅当 a1⊕a2⊕...⊕an≠0 a_1 \oplus a_2 \oplus ... \oplus a_n \not= 0

证明

  1. 操作到最后时,每堆石子数都是 00 , 0⊕0⊕...⊕0=00 \oplus 0 \oplus ... \oplus 0 = 0

  2. 如果 a1⊕a2⊕...⊕an=x≠0a_1 \oplus a_2 \oplus ... \oplus a_n = x \not= 0 ,那么肯定可以通过从某一堆中拿走若干颗石子后,将异或结果变成 00

    证明:我们先假设 xx 的最高一位的 11 在第 kk 位, 那么在 a1,a2,...,ana_1,a_2,...,a_n 中,一定存在一个 aia_i ,它的第 kk 位为11, ai⊕xa_i\oplus x一定是小于aia_i的,那么在aia_i中取ai−(ai⊕x)a_i-(a_i\oplus x)颗石子,就可以得到a1⊕a2⊕...⊕an=0a_1\oplus a_2 \oplus ...\oplus a_n = 0

  3. 如果 a1⊕a2⊕...⊕an=0a_1\oplus a_2\oplus ...\oplus a_n = 0 ,那么无论怎么拿,最终的异或结果一定不为0

    反证法:假设从第i堆石子中拿了若干个,结果仍然为 00 先设第 ii 堆拿完后还剩 ai′{a_i}' 颗石子,由于不能不拿,所以 0<ai′<ai0\lt {a_i}' \lt a_i ,而且 a1⊕a2⊕...⊕ai′⊕...⊕an=0a_1\oplus a_2\oplus ... \oplus {a_i}' \oplus ...\oplus a_n = 0 , 那么 (a1⊕a2⊕...⊕ai⊕...⊕an)⊕(a1⊕a2⊕...⊕ai′⊕...⊕an)=0(a_1\oplus a_2\oplus ... \oplus a_i \oplus ...\oplus a_n )\oplus (a_1\oplus a_2\oplus ... \oplus {a_i}' \oplus ...\oplus a_n ) = 0, 则 ai′⊕ai=0{a_i}' \oplus a_i = 0 ,也就是 ai′=ai{a_i}'=a_i ,和 0<ai′<ai0\lt {a_i}' \lt a_i 矛盾

那么如果 a1⊕a2⊕...⊕an=x≠0a_1 \oplus a_2 \oplus ... \oplus a_n = x \not= 0 ,那么先手总可以从某堆拿走若干颗石子,使得 a1⊕a2⊕...⊕an=0a_1\oplus a_2\oplus ...\oplus a_n = 0 ,那么最终后手一定没有石子可以拿,则先手必胜 否则,无论先手怎么拿,都会使得 a1⊕a2⊕...⊕an≠0a_1\oplus a_2\oplus ...\oplus a_n \not= 0 ,那么此时后手就变成了先手,所以最初的先手必败

Code

C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int k,n,ans,x;
    scanf("%d",&k);
    while (k--)
    {
    	ans=0;
    	scanf("%d",&n);
	    while (n--)
	    {
	        scanf("%d",&x);
	        ans^=x;
	    }
	    if (ans) puts("Yes");
	    else puts("No");
	}
    return 0;
}
原文