Given the level-order listing of the rational number tree, find the n-th fraction and the position of a given fraction.
Medium4TreeBFSHash mapInterviewNo attempts yetTime limit5sMemory limit512 MBConsider an infinite complete binary tree whose root is 1/1, where the left child of the node p/q is p/(p+q) and the right child is (p+q)/q. The top of the tree looks like this.
1/1
______|______
| |
1/2 2/1
___|___ ___|___
| | | |
1/3 3/2 2/3 3/1
...
Every positive rational number is known to appear in this tree exactly once. Traversing the tree in level order gives the following array.
1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, ...
Answer the following two kinds of queries.
The first line contains the number of test cases T. The next T lines each hold one test case. Each line contains a query id (1 or 2) and one or two integers.
Print one line for each test case.
Case #x: p q, where x is the test case number starting from 1, and p and q are the numerator and the denominator of the requested element.Case #x: n, where x is the test case number and n is the position of the given number.