博弈論經典問題,Nim遊戲是一個典型的組合遊戲問題,很多遊戲問題都可以規約到Nim遊戲問題。Nim遊戲問題是一個ICG(Impartial Combinatorial Games)問題;
ICG問題的特徵是:
1.兩個人蔘與,交替走棋;
2.可能的走法在一個有限的集合裏選取;
3.遊戲局面無後效性,未來與過去無關;
4.如果某選手無法走動,則判負;
Nim的理論
遊戲狀態只分兩種:當前先手必勝,當前先手必敗;前者稱爲N位置,後者稱爲P位置;
更爲嚴謹的定義是:
終止狀態是P位置;
能夠移動到P位置的狀態時N位置;
只能到N位置的狀態時P位置;
Nim問題的解法:
所有堆的石子數目求異或;爲0則是P位置;
證明:
1,終止狀態所有位置都爲0,是P位置;
2,對於一個異或爲非0的N位置是能夠移動到P位置的(這個還沒有想明白……(~ o ~)~zZ);
3,異或爲0的P位置只能移動到N位置,因爲對其進行異或運算得到的只能是非0的;
證明完了,用最基本的Nim遊戲問題驗證一下。
PKU的2234_Matches Game
Matches Game
Time Limit:
1000MS |
|
Memory Limit:
65536K |
Total Submissions:
4453 |
|
Accepted:
2483 |
Description
Here
is a simple game. In this game, there are several piles of matches and
two players. The two player play in turn. In each turn, one can choose a
pile and take away arbitrary number of matches from the pile (Of course
the number of matches, which is taken away, cannot be zero and cannot
be larger than the number of matches in the chosen pile). If after a
player’s turn, there is no match left, the player is the winner. Suppose
that the two players are all very clear. Your job is to tell whether
the player who plays first can win the game or not.
Input
The
input consists of several lines, and in each line there is a test case.
At the beginning of a line, there is an integer M (1 <= M <=20),
which is the number of piles. Then comes M positive integers, which are
not larger than 10000000. These M integers represent the number of
matches in each pile.
Output
For each test case, output "Yes" in a single line, if the player who play first will win, otherwise output "No".
Sample Input
2 45 45
3 3 6 9
Sample Output
No
Yes
Source
代碼如下: