现在的位置: 首页 > 综合 > 正文

2234 Matches Game 尼姆博弈

2013年12月04日 ⁄ 综合 ⁄ 共 2126字 ⁄ 字号 评论关闭

2234 Matches Game

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

随机博弈指的是这样的一个博弈游戏,目前有任意堆石子,每堆石子个数也是任意的,双方轮流从中取出石子,规则如下:

1)每一步应取走至少一枚石子;每一步只能从某一堆中取走部分或全部石子;

2)如果谁取到最后一枚石子就胜。

也就是尼姆博弈(Nimm Game

必败局面:也叫奇异局势无论做出何出操作,最终结果都是输的局面。必败局面经过2次操作后,可以达到另一个必败局面。

必胜局面:经过1次操作后可以达到必败局面。

即当前局面不是必败局面就是必胜局面,而必胜局面可以一步转变成必败局面。

最终状态:
1最后剩下一堆石子;(必胜局面)

2剩下两堆,每堆一个;(必败局面)

3当石子剩下两堆,其中一堆只剩下1颗,另一堆剩下多于n颗石子时,当前取的人只需将多于1颗的那一堆取出n-1颗,则局面变为刚才提到的必败局面。(必胜局面)

判断当前局势是否为必胜(必败)局势:
1)把所有堆的石子数目用二进制数表示出来,当全部这些数按位异或结果为0时当前局面为必败局面,否则为必胜局面;
2
)在必胜局面下,因为所有数按位异或的结果是大于零的,那么通过一次取,将这个(大于其它所有数按位异或的结果的)数下降到其它所有数按位异或的结果,这时局面就变为必败局面了。

定理:一组自然数中必然存在一个数,它大于等于其它所有数按位异或的结果。

证明:原命题等价于,设a1a2... an=pp≠0时,必存在k,使得akp<ak(当p=0时,对于任意的k,有akp=ak)。
p的最高位是第q位,则至少存在一个k,使得ak的第q位也是1,而ak
p的第q位为0,所以ak^p<ak
   
补缀一点,(a
bb=abb=a0=a,所以akp相当于“其它所有数按位异或的结果”。

参考:https://sites.google.com/site/lene13/Home/sophi-mass/0-7

12 45 45

45450,4545的异或等于0

23 3 6 9

局势(3,69)因为369不等于0,所以这是一个必胜局势。

 3 011

6 110

 5 101 

即从第3堆中的9个中取走954个,则(3,69)->(3,65),3650,故(3,65)为奇异局势,即从必胜局势转变成必败局势。

 

源代码:

 

#include<iostream>
using namespace std;
int temp[ 20 ];
int main()
{
    int i, n, min;
    while( cin >> n )
    {
        for( i = 0; i < n; i++ )
            cin >> temp[ i ];
        min = temp[ 0 ];
        for( i = 1; i < n ; i++ )
            min = min^temp[ i ];
        if( min == 0 )
            cout << "No" << endl;
        else
            cout << "Yes" << endl;
    }
    return 0;
}

抱歉!评论已关闭.