Snmmer day 9 尼姆博弈

今天上午訓練賽,果斷水過,一道題都沒有成功AC,慚愧,不發題解了。還是安靜地看看基礎。學學Nimm博弈。

Nimm Game

傳說中的博弈論入門題目。
首先有幾個概念:

奇異

用(a,b,c)表示某種局勢,首先(0,0,0)顯然是奇異局勢,無論誰面對奇異局勢,都必然失敗。第二種奇異局勢是(0,n,n),只要與對手拿走一樣多的物品,最後都將導致(0,0,0)。仔細分析一下,(1,2,3)也是奇異局勢,無論對手如何拿,接下來都可以變爲(0,n,n)的情形。

局勢轉換

從一個非奇異局勢向一個奇異局勢轉換的方式可以是:
1)使 a = c xor b;
2)使 b = a xor c;
3)使 c = a xor b.
至於爲什麼?尼姆博弈的數學理論-Wiki

例1 (14,21,39),14(+)21=27,39-27=12,所以從39中拿走12個物體即可達到奇異局勢(14,21,27)。
例2 (55,81,121),55(+)81=102,121-102=19,所以從121中拿走19個物品就形成了奇異局勢(55,81,102)。
例3 (29,45,58),29(+)45=48,58-48=10,從58中拿走10個,變爲(29,45,48)。
Game Play:original(7,8,9)
甲:(7,8,9)->(1,8,9)奇異局勢
乙:(1,8,9)->(1,8,4)
甲:(1,8,4)->(1,5,4)奇異局勢
乙:(1,5,4)->(1,4,4)
甲:(1,4,4)->(0,4,4)奇異局勢
乙:(0,4,4)->(0,4,2)
甲:(0.4,2)->(0,2,2)奇異局勢
乙:(0,2,2)->(0,2,1)
甲:(0,2,1)->(0,1,1)奇異局勢
乙:(0,1,1)->(0,1,0)
甲:(0,1,0)->(0,0,0)奇異局勢
甲勝。

接下來看看OJ題:

POJ 2234

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
給出M個Nimm堆,問先手是否得勝。

#include <cstdio>
using namespace std;
int main(){
    int m,ans,n;
    while(~scanf("%d",&m)){
        n=ans=0;
        scanf("%d",&n),ans^=n;
        //printf("ans=%d\n",ans);
        if(ans)printf("Yes\n");
        else printf("No\n");
    }
}

不斷讀取新數進行異或操作,最後結果爲0則先手不勝,不爲0則先手勝利。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章