hdu 1907 (尼姆博弈)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1907

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
 
解题思路:尼姆博弈,不过这题需要特判下是否全为1的情况,如果全为1,根据n的奇偶来判定。

1、问题模型:有三堆各若干个物品,两个人轮流从某一堆取任意多的物品,规定每次至少取一个,多者不限,最后取光者得胜。

2、解决思路:用(a,b,c)表示某种局势,显证(0,0,0)是第一种奇异局势,无论谁面对奇异局势,都必然失败。第二种奇异局势是(0,n,n),只要与对手拿走一样多的物品,最后都将导致(0,0,0)。

  搞定这个问题需要把必败态的规律找出:(a,b,c)是必败态等价于a^b^c=0(^表示异或运算)。

  证明:(1)任何p(a,b,c)=0的局面出发的任意局面(a,b,c’);一定有p(a,b,c’)不等于0。否则可以得到c=c’。

      (2)任何p(a,b,c)不等于0的局面都可以走向 p(a,b,c)=0的局面

       (3)对于 (4,9,13) 这个容易验证是奇异局势 

             

       其中有两个8,两个4,两个1,非零项成对出现,这就是尼姆和为  零的本质。别人要是拿掉13里的8或者1,那你就拿掉对应的9  中的那个8或者1;别人要是拿        掉13里的4,你就拿掉4里的4;  别人如果拿掉13里的3,就把10作分解,然后想办法满 足非零项成对即可。

3、推广一:如果我们面对的是一个非奇异局势(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)

4、推广二:当石子堆数为n堆时,则推广为当对每堆的数目进行亦或之后值为零是必败态。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<map>;
using namespace std;
int n,m,a[100005];
int main(){
    int T;
    cin>>T;
    while(T--){
        cin>>n;
        int flag=0;
        for(int i=1;i<=n;i++){
            cin>>a[i];
            if(a[i]!=1)flag=1;
        }
        if(!flag){
            if(n%2)puts("Brother");
            else puts("John");
            continue;
        }
        int ans=0;
        for(int i=1;i<=n;i++)
            ans^=a[i];
        if(ans)puts("John");
        else puts("Brother");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zjl192628928/p/10485916.html