Alternative Permutations
Time limit8sMemory limit256 MB
Given k, find the smallest n for which some BST on 1 to n is produced by exactly k permutations, and print the lexicographically smallest one.
- Level
Hard9 of 10
- Topics
- Combinatorics, Tree, Dynamic programming, Recursion
- Solved
- No attempts yet
Problem
Johnny wrote a permutation to binary search tree (BST) converter. Given a permutation , it assigns to the root. From the numbers in that are smaller than , it recursively builds a BST, keeping their original order, and attaches it as the left subtree of the root. Symmetrically, from the numbers larger than , it builds a BST and attaches it as the right subtree. To Johnny's surprise, different permutations can produce the same BST. For instance, and produce the same BST. Surprised by this fact, he defined Johnny's Numbers : the -th Johnny's Number is the smallest such that some BST on nodes labelled can be obtained from exactly different permutations of . Studying Johnny's Numbers is hard, and interest in them is fading. Help Johnny compute for a given .
Input
The first line contains a natural number ().
Output
On the first line, print a positive integer , provided that it exists and is at most . On the second line, print the integers of the lexicographically smallest generating permutation among the permutations. Otherwise, that is, if does not exist or is larger than , print the word NIE (Polish for 'no').
Hint
The tree having exactly eight generating permutations is shown below:
All permutations generating that tree are: , , , , , , , .