TREE2 - Which is Next

no tags 

Every computer science student knows binary trees. Here is one of many possible definitions of binary trees. Binary trees are defined inductively. A binary tree t is either an external node (leaf) o or an ordered pair t = (t1, t2) representing an internal node * with two subtrees attached, left subtree t1 and right subtree t2. Under this definition the number of nodes in any binary tree is odd. Given an odd integer n let B(n) denote the set of all binary trees with n nodes, both internal and external. For instance B(1) consists of only one tree o, B(3) = {(o, o)} and B(5) = {(o, (o, o)), ((o, o), o)}. The trees of B(5) are depicted in the figure below.

The trees B(5)

Denote by |t| the number of nodes in a tree t. Given a tree t we define its unique integer identifier N (t) as follows:

  • N (o) = 0
  • N (t1, t2) = 2|t1|+|t2| + 2|t2| * N(t1) +N (t2)

For instance, N (o,o) = 22 + 21 * 0 + 0 = 4, N (o, (o, o)) = 24 + 23 * 0 + 4 = 20,
N ((o, o), o) = 24 + 21 * 4 + 0 = 24.

Consider the following linear order on all binary trees:

1) o < = t
2) (t1, t2) < = (u1, u2) when t1 < u1, or t1 = u1 and t2 < = u2

In this order a single leaf o is the smallest tree and given two nonleaf trees, the smaller one is that with the smaller left tree, if the left subtrees are different, and that with the smaller right subtree, otherwise. Hence for instance (o, (o, o)) < ((o, o), o), since we have o < (o, o). Assume now that the trees in B(n) were sorted using the relation < =. Then, for each tree t in B(n) we define the successor of t as the tree that immediately follows t in B(n). If t is the largest one in B(n) then the successor of t is the smallest tree in set B(n). For instance, the successor of (o, o) in B(3) is the same tree (o, o) and the successor of (o, (o, o)) in B(5) is ((o, o), o). Given the integer identifier of some tree t can you give the identifier of the successor of t in B(|t|)?


Write a program that:

  • reads the identifier of some binary tree t,
  • computes the identifier of the successor of t in B(|t|),
  • writes the result.


The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first and only line of the input contains one integer n (0 <= n < = 230) - the identifier of some binary tree t.


For each test case the first and only line of the output should contain one integer s - the identifier of the successor of t in B(|t|).


Sample input:
Sample output:

Added by:adrian
Time limit:0.347s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: NODEJS PERL6 VB.NET
Resource:ACM Central European Programming Contest, Warsaw 2003