HDU 1907 John (Nim博弈)

John

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 2034    Accepted Submission(s): 1096


Problem Description
Little John is playing very funny game with his younger brother. There is one big box filled with M&Ms of different colors. At first John has to eat several M&Ms of the same color. Then his opponent has to make a turn. And so on. Please note that each player has to eat at least one M&M during his turn. If John (or his brother) will eat the last M&M from the box he will be considered as a looser and he will have to buy a new candy box.

Both of players are using optimal game strategy. John starts first always. You will be given information about M&Ms and your task is to determine a winner of such a beautiful game.

 

 

Input
The first line of input will contain a single integer T – the number of test cases. Next T pairs of lines will describe tests in a following format. The first line of each test will contain an integer N – the amount of different M&M colors in a box. Next line will contain N integers Ai, separated by spaces – amount of M&Ms of i-th color.

Constraints:
1 <= T <= 474,
1 <= N <= 47,
1 <= Ai <= 4747

 

 

Output
Output T lines each of them containing information about game winner. Print “John” if John will win the game or “Brother” in other case.

 

 

Sample Input
2 3 3 5 1 1 1
 

 

Sample Output
John Brother
 

 

Source
 

 

Recommend
lcy
 

 

尼姆博奕(Nimm Game):有三堆各若干个物品,两个人轮流从某一堆取任意多的物品,规定每次至少取一个,多者不限,最后取光者得胜。

这种情况最有意思,它与二进制有密切关系,我们用(a,b,c)表示某种局势,首先(0,0,0)显然是奇异局势,无论谁面对奇异局势,都必然失败。第二种奇异局势是
(0,n,n),只要与对手拿走一样多的物品,最后都将导致(0,0,0)。仔细分析一下,(1,2,3)也是奇异局势,无论对手如何拿,接下来都可以变为(0,n,n)的情
形。

    计算机算法里面有一种叫做按位模2加,也叫做异或的运算,我们用符号(^)表示这种运算。这种运算和一般加法不同的一点是1^1=0。先看(1,2,3)的按位模2加的结
果:

1 =二进制01
2 =二进制10
3 =二进制11 (^)
———————
0 =二进制00 (注意不进位)

    对于奇异局势(0,n,n)也一样,结果也是0。任何奇异局势(a,b,c)都有 a ^ b ^ c =0。如果我们面对的是一个非奇异局势(a,b,c),

要如何变为奇异局势呢?假设 a < b< c,我们只要将 c 变为  a ^ b,即可,因为有如下的运算结果:  a ^ b ^( a ^ b)=(a ^ a) ^ ( b ^ b ) = 0 ^ 0 = 0。

要将c 变为a ^ b,只要从 c中减去 c -(a ^ b)即可。

 

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

int main(){

    //freopen("input.txt","r",stdin);

    int t,n;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        int ans=0,flag=0,x;
        for(int i=0;i<n;i++){
            scanf("%d",&x);
            ans^=x;
            if(x>1)     //当所有数据都为1时的特判
                flag=1;
        }
        if(flag){
            if(ans==0)
                puts("Brother");
            else
                puts("John");
        }else{
            if(n&1)
                puts("Brother");
            else
                puts("John");
        }
    }
    return 0;
}

 

posted @ 2013-08-02 11:27  Jack Ge  阅读(1051)  评论(0编辑  收藏  举报