eolymp
bolt
Try our new interface for solving problems
Problems

Catacombs

Catacombs

The Pirate's catacombs on the island of Treasures were tunneled on such principle. After the hidden entrance located a cave from which two tunnels go out -- to the left and to the right. Each of tunnels ends with a cave from which two tunnels go out also, and etc. The length of each tunnel is equal to one. Eventual caves are in the distance \textbf{D} from an entrance. These caves do not have subsequent outputs. Tunnels between itself do not intersect, and does not conduce to one cave. The number \textbf{D} is named as depth of catacombs. \includegraphics{https://static.e-olymp.com/content/63/6313dea2edd831a77597fd17a1dbf9b306f04a6b.jpg} It is hidden one box with treasure in each of eventual caves. Pirates decided to move these boxes pursuant to the last pointing of Captain Jeck Sperrou before he will arrive on the island. Pirates drew the plan of catacombs and numbered eventual caves from left to right. Then for every treasure was the number of cave in which he must find oneself before Captain will arrive. In every cave again will find only one box after moving. Pirates can only exchange between itselfs boxes from two caves to provide safety of treasures. It is possible to begin other only upon termination of one exchange. It is necessary to find the least total distance which pirates needed to carry boxes, that to place their in necessary rank. \InputFile The first line contains the depth of catacombs \textbf{D} (\textbf{D} ≤ \textbf{8}). The second line contains \textbf{2^D} different integers from \textbf{1} to \textbf{2^D}. Every \textbf{i} of them identifies the number of cave in which must to be situated the box, which is in a cave with number \textbf{i} at first. \OutputFile The first line contains the minimum total distance which will be passed by pirates with treasures. Second line contains an integer \textbf{K} - the proper quantity of exchanges. Each of the next \textbf{K} lines contains two numbers, the cave numbers between which the exchange takes place. The exchanges must be printed in the order they occur.
Time limit 2 seconds
Memory limit 64 MiB
Input example #1
2
3 4 2 1
Output example #1
20
3
1 3
2 4
1 2

Example description: Сначала поменяем местами сокровища в пещерах 3 и 4. Пройдено расстояние 4 (по 2 для каждого сундука). Потом поменять сокровища в пещерах 4 и 1, и 3 и 2. Расстояние в обоих случаях – 8. Таким образом – все станут на свои места, а суммарное расстояние будет

Author Andrey Korotkov
Source 2008 XXI All-Ukrainian Informatics Olympiad, Lvov, April 5 - 11, Round 2