1. 程式人生 > >hdu1907John(nim博弈)

hdu1907John(nim博弈)

John

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


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

題意:有n給糖果,每種有ai顆,兩個人每次都從一堆中吃幾顆,不能不吃。吃掉最後一顆的人算輸。John先吃,問最後誰會贏。

題解:nim博弈。先手必勝的結論有兩個:(1)當所有種類糖果數量都是1的時候,就先手必勝,因為你拿一個我拿一個,最後一個肯定是另一個人拿的。(2)有充裕堆(存在一堆中的糖果數大於1的情況)的時候,異或和為0,先手必敗,不為0,先手必勝。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4     int t;
 5     while(~scanf("%d",&t))
 6     {
 7         while(t--)
 8         {
 9             int n;
10             scanf("%d",&n);
11             int ai;
12             int ans=0;int num=0;
13             for(int i=0;i<n;i++)
14             {
15                 scanf("%d",&ai);
16                 ans=ans^ai;
17                 if(ai>1)num++;
18             }
19             if(num)//有充裕堆,異或和不為0勝 
20             {
21                 if(ans==0)printf("Brother\n") ;
22                 else printf("John\n");
23             }
24             else
25             {
26                 if(ans==0)//有偶數個,且每個都為1 
27                 {
28                     printf("John\n");
29                 }else
30                 {
31                     printf("Brother\n") ;
32                 }
33             }
34         }
35     }
36     return 0;
37 }