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) ;
or a single ordered pair
(t1, t2) of two binary trees, left
subtree t1 and right subtree t2 respectively,
called an internal node.
Given an integer n, B(n) is the set of trees with n
leaves. For instance, the picture below shows the two trees of
B(3) = {(
,(
,
)),((
;,
),
)}.
Observe that those trees both have two internal nodes and a total of five nodes.
Given a tree t we define its unique integer identifier N(t):
For instance, we have
N(,
) = 22 + 21×0 + 0 = 4,
N(
,(
,
)) = 24 + 23×0 + 4 = 20
and
N((
,
),
) = 24 + 21×4 + 0 = 24.
The ordering is defined on binary trees as follows:
![]() |
![]() |
t | |
(t1, t2) | ![]() |
(u1, u2), when t1 ![]() ![]() |
Hence for instance,
(,(
,
))
((
,
),
)
holds, since we have
(
,
).
Using the ordering , B(n) can be sorted.
Then, given a tree t in B(n),
we define S(t) as the tree that immediately
follows t in the sorted presentation of B(n), or as the smallest
tree in B(n), if t is maximal in B(n).
For instance, we have
S(
,
) = (
,
) and
S(
,(
,
)) = ((
,
),
).
By composing the inverse of N,S and N we finally define a partial
map on integers.
Write a program that computes s(n).
Input consists of several test cases, each of them following the description below. A blank line separates two consecutive cases.
The first input line contains an integer K, with K > 0.
It is followed by K lines, each specifying an integer ni with
1i
K and
0
ni < 231.
For each test case, the output should consist of K lines, the i-th output line being s(ni), or `NO' if s(ni) does not exist.
The outputs of two consecutive cases will be separated by a blank line.
5 4 0 20 5 432
4 0 24 NO 452