HDU3032_NimOrNotNim解題報告
HDU3032 Nim or not Nim 解題報告:思路與證明
胡明曉
Description
Alice and Bob is tired of playing Nim under the standard rule, so they make a difference by also allowing the player to separate one of the heaps into two smaller ones. That is, each turn the player may either remove any number of objects from a heap or separate a heap into two smaller ones, and the one who takes the last object wins.
Input
Input contains multiple test cases. The first line is an integer 1≤T≤100, the number of test cases. Each case begins with an integer N, indicating the number of the heaps, the next line contains N integers s00, s11, ...., sN?1N?1, representing heaps with s00, s11, ..., sN?1N?1 objects respectively.(1≤N≤106
Output
For each test case, output a line which contains either "Alice" or "Bob", which is the winner of this game. Alice will play first. You may asume they never make mistakes.
解題思路
Nim遊戲的SG函數計算如下:
g(x) = mex{g(y) | y是x的後繼狀態},其中mex S表示S中未出現的最小非負整數。
g(x0)=0。(x0為終止狀態)
設狀態用石子數向量(a1
將一堆石子分成兩堆,等於將一個一堆的Nim遊戲A變成兩個一堆遊戲的和B,這兩個一堆遊戲之和也是A的後繼狀態。計算A的SG函數時,除了考慮普通後繼狀態之外,還要將B的SG值加入mex計算,而B的SG值是兩個成員遊戲SG值的異或◎(根據和遊戲定理)。
下面計算單堆狀態的SG函數。
g(0)=0,
g(1)=mex{g(0)}=1,
g(2)=mex{g(0), g(1), g(1,1)}=mex{ g(0), g(1), g(1)◎g(1))=2,
g(3))=mex{g(0), g(1), g(2), g(1)◎g(2))=mex{0,1,2,3}=4,
g(4)=mex{g(0), g(1), g(2), g(3), g(1)◎g(3)), g(2)◎g(2))=mex{0,1,2,4,5,0}=3,
g(5)=mex{g(0), g(1), g(2), g(3), g(4), g(1)◎g(4), g(2)◎g(3))
=mex{0,1,2,4,3, 1◎3, 2◎4}=5,
g(6)=mex{0,1,2,4,3, 5, 1◎5, 2◎3, 4◎4}=6,
g(7)=mex{0,1,2,4,3, 5, 6, 1◎6, 2◎5, 4◎3}=8,
g(8)=mex{0,1,2,4,3, 5, 6, 8,1◎8, 2◎6, 4◎5, 3◎3}=7,
g(9)=mex{0,1,2,4,3,5,6,8,7, 1◎7, 2◎8, 4◎6, 3◎5}=9,
……
發現規律是g(a)=a,但g(4k+3)與g(4k+4)的值對調一下。即
g(a)=a (a=4k+1或4k+2)
g(a)=4k+4 (a=4k+3) (*)
g(a)=4k+3 (a=4k+4)
嚴格的證明如下。
證明:設a=4k+r(r=1,2,3,4),k=0,1,……,即按k分成4個一組,對組號k進行數學歸納。
為敘述方便,將後繼狀態的SG值集合劃分成兩類:S1和S2,分別表示單狀態和分解狀態的值,即S1={g(0),g(1),…g(a-1)},S2={g(a1)◎g(a2) | a1+a2=a,a1>0,a2>0}。g(a)=mex S=mex(S1∪S2)。
當k=0時,顯然成立。
假設當k<=m時(*)式成立,於是可以列出非零狀態a和g(a)的二進制末兩位後綴對應情況,如下表:
表1
a |
00 |
01 |
10 |
11 |
g(a) |
11 |
01 |
10 |
00 |
進一步,a1、a2和g(a1)◎g(a2)的二進制末兩位後綴對應情況如下表:
表2
a2 g(a1)◎g(a2) a1 |
00 |
01 |
10 |
11 |
00 |
11◎11=00 |
11◎01=10 |
11◎10=01 |
11◎00=11 |
01 |
01◎11=10 |
01◎01=00 |
01◎10=11 |
01◎00=01 |
10 |
10◎11=01 |
10◎01=11 |
10◎10=00 |
10◎00=10 |
11 |
00◎11=11 |
00◎01=01 |
00◎10=10 |
00◎00=00 |
當k=m+1時,對k組的4個狀態a分別證明。
(1)a=4k+1
a的後綴是01,由歸納假設,S1中0,1,…,a-1各出現一次,而S2中只有10後綴的值,沒有01後綴的值(見表2陰影格子),所以g(a)=a。符合(*)式結果。
(2)a=4k+2
a的後綴是10,由歸納假設及情形(1),S1中0,1,…,a-1各出現一次,而S2中有00、01後綴的值,沒有10後綴的值(見表2),所以g(a)=a。符合(*)式結果。
(3)a=4k+3
a的後綴是11,由歸納假設及情形(1)(2),S1中0,1,…,a-1各出現一次,而S2中全是11後綴的值(見表2),而且能取到a值本身(作分解a=1+(a-1)即能),所以g(a)=a+1=4k+4。符合(*)式結果。
(4)a=4k+4
a的後綴是00,由歸納假設及情形(1)(2)(3),S1中0,1,…,a-2,a各出現一次,a-1沒出現,而S2中有00、01後綴的值,沒有11後綴的值(見表2),也不可能出現a-1,所以g(a)=a-1=4k+3。符合(*)式結果。
總之,k=m+1時,(*)式也成立。證畢。
參考代碼:
(待加)
HDU3032_NimOrNotNim解題報告