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,先手必胜。

反nim博弈的结论

 1 #include
 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)
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 }

 

转载于:https://www.cnblogs.com/fqfzs/p/9909214.html

你可能感兴趣的:(java,数据结构与算法)