Bad Tree
Time limit1sMemory limit1024 MB
Find the kth lexicographically smallest permutation of 1 to n that, inserted into a BST in order, produces a tree of height n-1.
- Level
Medium6 of 10
- Topics
- Combinatorics, Dynamic programming, Tree
- Solved
- No attempts yet
Problem
Binary search trees speed up searches only when the height of the tree is much smaller than the number of values stored in it. Judges, however, try to build worst case data. So in binary search tree problems, the judges almost always create data where nodes are inserted in a particular order that makes the tree height the worst possible, .
Without loss of generality, let the values to insert be 1, 2, 3, ..., n. For , inserting the values in the order 5, 1, 4, 3, 2 gives a binary search tree of height 4.

Many permutations of the integers 1 through produce a tree of height when inserted in that order. Write a program that finds the th permutation in lexicographical order among them.
Input
The input is a single line with two space-separated integers () and (). is the number of nodes, and is the position of the wanted permutation in lexicographical order.
Output
Print the th permutation of the integers 1 through that, when inserted into a binary search tree in that order, produces a tree of height . Print the numbers on one line, with a space after each number. If no such permutation exists, print -1.