The beauty of programming----NIM Games

Source: Internet
Author: User

: Game games · Nim game time limit: 10000ms single point time limit: 1000ms memory limit: 256MB description

Today we're going to meet a couple of new friends, Alice and Bob.
Alice and Bob are always doing a variety of games, and today they are playing a game of stone.
In this game, Alice and Bob Place n heaps of different stones, numbered 1. N, there are a[i] stones in the first heap.
Every action, Alice and Bob can choose to remove any number of stones from a heap of stones. Take at least 1, and remove all the remaining stones from the heap.
Alice and Bob take turns, and the man who takes the last stone wins.
Assuming that each game is Alice's first action, would you judge who will win if the two sides are smart enough in a given situation?

Input

Line 1th: an integer n. Represents the number of gravel heaps. 1≤n≤100
Line 2nd: n integers, and the number of the first integer represents the a[i],1≤a[i]≤10000 of the heap of stones.

Output

Line 1th: A string, if Alice can win the output "Alice", otherwise output "Bob"

Sample input
33 2 1
Sample output
Bob

Problem Solving Report:
The topic is very simple, but the analysis is very interesting ... Let's look at the analysis below!
For a[i---N] for example:
3 011
2 010
1 001 --"in a state of equilibrium so Alice will break the balance regardless of how the value is taken, so Bob win

Looking at a few: 3 4 5 6
3 011
4 100
5 101
6 1 --"in an unbalanced, so Alice just need to dig out a value, so that it remains flat mark!"

----always with a word, keep the balance, win

Code:
1#include <stdio.h>2     intMain () {3         intn,res,tmp;4          while(SCANF ("%d", &n)! =EOF) {5res=0;6              while(n--){7scanf"%d",&tmp);8res^=tmp;9             }TenPuts (res==0?"Bob":"Alice"); One         } A         return 0; -}

The following is a detailed analysis:

An overview of the Nim game:

Do you remember this game?
Given the N-column pearls, the two took turns to take pearls, each time in a column to take at least 1 pearls, but not in two columns to take. Finally the man who took the Pearl lost.
Later, in a piece of information, this game is called "(Nim)". It is said that it originated in China and was rumored to be a slave worker who was trafficked to the Americas. Hard workers, in the spare time of work, with stones to play games to relieve loneliness. Later spread to the senior people, then use pennies (pennies), play on the bar counter.
The most famous play is to put 12 pennies into 3, 4, 53 columns, the people who win the light copper. Later, we found that the first to take a person in the 3 column to take away 2 pieces, become 1, 4, 5, can be a win-win, the game becomes uninteresting. So we increase the number of columns, increase the number of copper, so that people have an irregular feeling, not easy to grasp.
Until the beginning of this century, Charles Rionard Bauton (chales Leonard Bouton), an associate professor of mathematics at Harvard University, presented a very detailed analysis and proof that the general law of the game was solved by using the binary notation of numbers.
The general rule is that the person who takes the light copper coin wins.
Its variant is the rule of the people to lose the light copper, as long as the attention of a particular form (only 1 columns not 1), you can!
A lot of people put this method into a computer program, to fight with people, I do not know the people are fooled around, all marvel at the computer's magical greatness. In fact, just because it calculates faster than the human, the number of the conversion of the binary system of its speed is not as fast as it can be.
(above from K12 Education Forum)

The mathematical theory of Nim game is discussed:

Nim game is the most classical model in game theory, it has very simple rules and extremely beautiful conclusion.
The Nim game is a combination game (combinatorial games), which, to be exact, belongs to "impartial combinatorial" (hereinafter referred to as ICG). The game that meets the following conditions is ICG (probably less rigorous): 1, two players, 2, two players alternately move the game (move), one step at a time, the player can (generally) a limited number of legal moves in the set of any one of the mobile; 3, for any possible situation of the game, The legitimate move collection depends only on the situation itself, and does not depend on the player's operation, any previous operations, the number of dice, or any other factor; 4. If a player moves and the legal movement set of the situation is empty (that is, it cannot be moved at this time), the player is negative. According to this definition, many of the daily games are not ICG. For example, chess does not meet the condition 3, because the red side can only move the red son, Black can only move sunspots, the legal movement of the set depends on the player's turn to operate.

The usualthe definition of the Nim gameThat is true:There are a number of stones, the number of stones per heap is limited, the legal movement is "choose a heap of stones and take away a few (not to take)", if the turn of a person when all the gravel heap has been emptied, then the negative (because he does not have any legal movement).
The game looks a little complicated, let's start with a simple case study. If it is your turn, leaving only a heap of stones, then the winning strategy at this time must be to take this heap of stones all take one and not to the opponent left, and then the opponent lost. If there are two piles of unequal stones, the winning strategy is to make the two piles equal by taking a pile of pebbles, and if the opponent takes a number of them in a heap, you can take the same number of stars in the other pile until you win. If you are faced with two piles of equal stones, then you do not have any strategy to win, but the opponent can follow the above strategy to ensure victory. If it's three piles of stone ... It seems difficult to analyze, it seems we have to rely on some other useful (preferably stylized) analysis methods, or we would better be able to design a winning strategy can find a winning strategy algorithm.

define P-position and N-position, where p represents previous,n on behalf of next. Intuitively speaking, the last move of the people have a winning strategy situation isP-position, i.e. "Can be guaranteed to win "or" the initiator will be defeated, now turn to move people have the winning strategy situation isN-position, i.e. "The initiator is guaranteed to win. "A more rigorous definition is: 1. No moving situation (i.e. terminal position) is P-position ; 2. The situation that can be moved to P-position is n-position;3. All movement leads to n-position situation is p-position.
By this definition, if the situation is impossible to reproduce, or if the positions collection can be topological sorted, then each position is either p-position or n-position, and can be computed by definition.

Take the Nim game as an example to do some calculations. For example, I just said that when there are only two piles of stone and two piles of stone equal when there is a winning strategy, that is, this is a p-position, the following we rely on the definition of proof (3,3) is a p is a p is a p-position. First (3,3) sub-situation (that is, through the legal movement can be caused by the situation) (0,3) (1,3) (2,3) (obviously the location of the exchange of stone heap does not affect its nature, so the (x, y) and (y,x) as the same situation), only need to calculate the nature of these three kinds of situation can be. (0,3) The sub-situation has (0,0), (0,1), (0,2), where (0,0) is obviously p-position, so (0,3) is n-position (as long as you find a sub-situation is p-position can be described as n-position). The successor (1,3) is p-position (because the only sub-situation (0,1) is n-position), so (1,3) is also n-position. It can also be proved that (2,3) is n-position. So all the 3,3 are n-position, it's p-position. By a simple mathematical induction, it is very hard to prove that "there are two piles of gravel when the situation is p-position and only when the number of these two stones is equal".

According to the above process, a recursive algorithm can be obtained-for the current situation, recursive calculation of its properties of all sub-conditions, if there is a certain sub-situation is p-position, then the move to this sub-situation is the winning strategy. Of course, you may have been acutely aware of the large number of overlapping sub-problems, so you can use DP or memory search methods to improve efficiency. But the problem is, with this algorithm, for the situation of a Nim game (A1,a2,..., an), in order to determine its nature and find a winning strategy, it is necessary to calculate the nature of O (A1*a2*...*an) situation, regardless of memory can not reduce the complexity of this time. So we need a more efficient way of judging the nature of the Nim game situation.

Just say the conclusion well.

(Bouton ' s theorem): For a Nim game situation (A1,a2,..., an), it is p-position when and only if a1^a2^...^an=0, where ^ represents XOR (XOR) Operation.

What, isn't it amazing? When I saw it, I thought it was magical, totally unreasonable, and it was related to the different or the operation. But the proof of this theorem is not complicated, basically it is according to two kinds of position proof.

According to the definition, it is proved that a method of judging the nature of position is correct, only three propositions are proved: 1, this judgment will all terminal position sentenced to p-position;2, According to this judgment is sentenced to n-position situation can be moved to a p-position;3, according to this judgment was sentenced to p-position situation can not move to a p-position.

The first proposition obviously, terminal position only one, is all 0, xor or still is 0.

The second proposition, for a situation (A1,A2,..., an), if the a1^a2^...^an!=0, there must be a certain legal movement, the AI will be changed into AI ' after satisfying A1^a2^...^ai ' ^...^an=0. As a a1^a2^...^an=k, there must be an AI, whose binary representation is 1 at the top of the K (otherwise the highest bit of k is how the 1 is obtained). Then Ai^k<ai must be set up. Then we can change AI to Ai ' =ai^k, at this time A1^a2^...^ai ' ^...^an=a1^a2^...^an^k=0.

The third proposition, for a situation (A1,A2,..., an), if the a1^a2^...^an=0, there must be no legal movement, the AI will be changed into AI ' after satisfying A1^a2^...^ai ' ^...^an=0. Because the XOR operation satisfies the extinction rate, the A1^a2^...^an=a1^a2^...^ai ' ^...^an can get Ai=ai '. So changing AI to Ai ' is not a legitimate move. The certificate is completed.

According to this theorem, we can judge the nature of a nim's situation in the time of O (n), and if it is n-position, we can find all the winning strategies in O (n) time. The NIM problem is basically the perfect solution.

(above from Baidu Encyclopedia)

The image of the Nim game is detailed:

Nim takes a game of two people facing several piles of coins (or stones). There are k>=1 piles of coins, each containing n1,n2, ... NK Coin. The goal of the game is to choose the last remaining coins. The rules of the game are as follows: 1. Two game players alternately play (Game man I and Game Man II); 2. When it is time for each player to take the time, select a bunch of these heaps and take at least one coin from the selected heap (the player can take all the coins from his chosen heap); 3. When all the heaps become empty heaps, the last player who takes the child is the winner. The variables in this game are the heap number k and the number of coins in each heap n1,n2, ... Nk. The corresponding combinatorial problem is determining whether the player I wins or the Player II win and how two players should take the child to ensure their winning (winning strategy). In order to further understand the NIM take the child game, we examine some special cases. If the game starts with just a bunch of coins, the player I wins by taking all the coins. There are now 2 stacks of coins and the number of coins is N1 and N2 respectively. The winner of the game does not lie in the value of N1 and N2, but on whether they are equal. Set n1! =n2, the game man I take away from the large pile of coins so that the number of coins equal, so, the game man I after each take the number of children with the player II equal and finally win. But if n1= N2, then: Game Man II as long as the number of players I take the amount of the same amount of coins in the other heap, the final winner will be the game Man II. In this way, two stacks of winning strategies have been found. Now how do we scale from two heap of sub-strategies to any number of heaps? First, recall that each positive integer has a corresponding binary number, for example: 57 (10) à111001 (2), namely: 57 (10) =25+24+23+20. As a result, we can assume that each pile of coins consists of a Zishi of 2 power. In this way, a large pile of 57 coins can be considered to be composed of various sub-stacks of 25, 24, 23 and 20 respectively. Now consider the size of the large piles of n1,n2, ... NK's General Nim takes a child game. Each of the number NI is represented as the second binary number (the number of digits equal, 0 in front of the unequal): N1 = as...a1a0n2 = bs...b1b0 ... Nk = MS...M1M0 If the number of Zishi of each size is even, we call the Nim take the child game to be balanced, and the corresponding bit addition is even called the equilibrium bit, otherwise called the non-equilibrium bit. Therefore, the NIM takes the child game to be balanced, when and only if:

As + BS + ... + MS is even

......

A1 + B1 + ... + M1 is even

A0 + B0 + ... + M0 is even

As a result, we can draw the winning strategy: the player I can win in the unbalanced sub-game, and the Player II can win in the balanced sub-game. We experimented with a pair of two coins of Nim taking a sub-game. The game is unbalanced at the start of the game. In this way, the game man I can pass a sub-mode so that he left the game after the Player II is a balance of the game, and then no matter how the game Man II to take the son, and then left to the player I must be a non-equilibrium game, so repeated, when the game Man II in the last state of equilibrium after taking the son, Game man I will be able to take all the coins at once and win. And if the game is at the beginning of the balance of the game, then take the child according to the above method, the final Player II can win. The following applies this winning strategy to consider the 4-heap NIM fetch child game. The size of each pile is 7,9,12,15 coin. In binary notation the numbers are: 0111,1001,1100 and 1111, respectively. You can then get the following table:

23 = 8

22 = 4

21 = 2

20 = 1

Heap of size 7 0 1 1 1
Heap of size 9 1 0 0 1
Heap of size 12 1 1 0 0
Heap of size 15 1 1 1 1
The balance condition of the game is that the game is a non-equilibrium sub-game, so the game man I will be able to win the game under the winning strategy to achieve the final victory. There are a number of ways in which game man I can take 11 coins from a 12-size heap, making the game balanced (see table below),

23 = 8

22 = 4

21 = 2

20 = 1

Heap of size 7 0 1 1 1
Heap of size 9 1 0 0 1
Heap of size 12 0 0 0 1
Heap of size 15 1 1 1 1
After that, regardless of how the Player II takes the child, the player I still makes the game balance after taking the child. In the same way, game man I can also choose the size of 9 heap and take 5 coins and the remaining 4, or, Game man I from the size of 15 of the heap took 13 pieces and left 2.

In the final analysis, the key to Nim's game is the state of the game at the start of the game (balanced or unbalanced) and whether the first player can play according to the winning strategy of the sub-game.

(The above is transferred from Rainco_shnu Baidu Space)

Write something about yourself below:

If the rules of the Nim game change a little bit, at most can only fetch K, how to deal with?

The method is to set the number of stones per heap mod (k+1).



The beauty of programming----NIM Games

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.