Bell Ringing
Time limit2sMemory limit256 MB
Print all permutations of 1 to n in the recursive insertion order where bell n sweeps each row left to right or right to left.
- Level
Easy3 of 10
- Topics
- Recursion, Implementation
- Solved
- No attempts yet
Problem
Method ringing is a way of ringing church bells, common in England. Suppose there are bells with different pitches. The bell highest in pitch gets number 1, the second highest gets number 2, and so on. Ringing all bells in some order, each of them exactly once, gives one row. For , the orders 1, 2, 3, 4, 5, 6 and 6, 3, 2, 4, 1, 5 are two different rows.
A performance is ideal when every possible row appears in it exactly once. Physics limits which rows can follow each other. A bell that has been rung carries considerable inertia, and the ringer can speed up or slow down its cycle only a little. Therefore the position of each bell can change by at most one between two consecutive rows.
The figure below shows a performance that respects the inertia of the bells but is not ideal. The trajectory of bell 1 is drawn in blue and the trajectory of bell 2 is drawn in brown.

Given , print an ideal performance whose first row is 1, 2, ..., .
Input
The first and only line contains an integer ().
Output
Many ideal performances exist for the same , so exactly one of them is accepted, defined as follows.
- For the sequence is the single row 1.
- Let be the sequence for . Build the sequence for by replacing each , in order, with rows: insert bell into each of the possible positions of . When is odd, go from the rightmost position to the leftmost one. When is even, go from the leftmost position to the rightmost one.
Print the rows of that sequence, one row per line. Separate the numbers of a row with single spaces.