Counting the Number of Trees
Time limit2sMemory limit256 MB
Count, modulo 1e9+7, the binary search trees on keys 1..N that the insertion procedure can produce with height at most K.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Tree, Combinatorics, Recursion
- Solved
- No attempts yet
Problem
A binary search tree (BST) is a tree in which every node has at most children. If the number written on a node is , then the left subtree of that node may store only numbers smaller than , and the right subtree only numbers larger than .
The following pseudocode describes a function that inserts a number into a BST.
insert(number X, node N)
if X is smaller than the number at node N
if N has no left child
create a new node containing X and make it the left child of N
else
insert(X, left child of N)
else (X is larger than the number at node N)
if N has no right child
create a new node containing X and make it the right child of N
else
insert(X, right child of N)
The first number inserted becomes the root, and for every number X inserted afterward, insert(X, root) is called.
The height of a tree is the number of nodes on the longest path from the root node to a leaf node. A leaf node is a node with no children.
You are going to insert the numbers from to into a BST. When the insertion order can be chosen freely, find the number of BSTs with height at most that can be produced. The root node of a BST is assumed to have height 1.
Inserting and inserting produce the same BST, while and produce different BSTs.
The number of cases can be very large, so print the answer modulo .
Input
The first line contains two integers and separated by a space. ()
Output
Print the number of possible BSTs modulo .