Tower of Hanoi

image

In 1883, Edouard Lucas invented, or perhaps reinvented, one of the most popular puzzle of all time —Tower of Hanoi, as he called it— and that nowadays, it is already used as prototype of recursive algorithm. In fact, a lot of computing science textbooks, use it as instance to implement the idea of recursion in a program. These are the rules of the game:

Although, naturally, the best way to initiate youself into the secrets of this puzzle is to try to solve it with one of many and varied real models that are found in the shops of presents, if it is not possible, a good way to capture the essence of the game is to write a program that shows us in the screen a model of the Tower of Hanoi and that allow us to simulate the movement of the disks. But it is not what we are going to propose in this task. The next step would be to write a program that solve us the puzzle in the most efficient way. Neither it is the aim of this task. The followed aim is the implementation of an efficient algorithm to know the state of solution of the game. To make easier the task, we do not ask for the detail of the disks that there are in each pole, but only how many there are after of determinated movement, when the puzzle is solved following a specifically algorithm, that we describe below.

It is perfectly known, and it is very easy to prove, that the minimal number of movements of disks that you have to do to complete the change of the original tower to another different pole is 2n12^n- 1, being nn the number of disks. A very simple algorithm, but that do not allow us to solve the puzzle in this quantity of movemements is the following one: for the odd movements, we take the smallest disk (we say number 1) of the pole where it is inserted and it is placed in the following one inside the circle succession ABCABCABCABC \dots; for the even movements, the only possible movement that does not involve the disk number 1 is done.

Input

The input file consists of a series of lines. Each one of them contains two integer numbers n,mn, m: nn is the number of disks and mm, that will be in the interval [0, 2n12^n - 1], will be the number of the last movement done. The file ends with a line that contains two zeros and that must not be processed.

Output

The output also consists of a series of lines, one for each line of the input file (except the last one). Each one of them will be formed by three integer numbers, that represent the number of disks of every pole AA, BB and CC respectively, after the movement mm, and remembering that those movements have been done according to the described algorithm.

Scoring

Problem information

Author: Unknown
Translator: Carlos Molina

Generation: 2026-01-25T11:11:32.401Z

© Jutge.org, 2006–2026.
https://jutge.org