hdu1907John(nim博弈)
阿新 • • 發佈:2018-11-05
John
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 6162 Accepted Submission(s): 3584
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.
Constraints:
1 <= T <= 474,
1 <= N <= 47,
1 <= Ai <= 4747
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 }