Folding Sheets
Time limit1sMemory limit32 MB
Given a number X or a position P, determine its counterpart in the sequence produced by folding an N x N sheet in half alternating bottom-over-top and right-over-left until 1 x 1, then reading the resulting column bottom to top. N is 2^K, K up to 31, and there are up to 10000 queries.
- Level
Medium7 of 10
- Topics
- Recursion, Divide and conquer, Implementation, Math
- Solved
- No attempts yet
Problem
You have a sheet of grid paper of size squares. is a power of two.
The squares are numbered from to , the top row first and left to right inside each row. Each square holds only its own number.
The sheet is folded in half over and over. The bottom half is folded over the top half first, then the right half over the left half, and the two moves alternate in that order until the folded sheet is .
The squares then form a column of size . Reading that column from its bottom square to its top square gives the sequence , where is the position in the sequence.
A developer sitting through a dull meeting folds sheets into such columns and wants answers to two questions.
- Question type 1. A number is given. At which position of the sequence does it sit?
- Question type 2. A position of the sequence is given. Which number sits there?
Write a program that computes the number or the position , depending on the type of the question.
Input
The first line contains the number of questions . Each of the next lines contains three integers , , , separated by a single space.
- is the type of the question. or .
- is the exponent that fixes the size of the sheet. The sheet is squares wide.
- is the number when , and the position when .
Output
Print lines, one per question. Each line holds a single integer, the position or the number , depending on the type of the question.
Constraints
- , where
Notes

For , reading the column from bottom to top gives .

For , .