Problem 620
Number of Ways to Reorder Array to Get Same BST
Hard · 30 pts · Tree, Binary Search Tree, Combinatorics, Divide and Conquer
Problem
Inserting the values of a permutation of 1..N one by one into an empty binary search tree builds a certain tree. Count the other orderings of the same values that build exactly the same tree, not counting the original ordering, modulo 1000000007. The first value must stay the root; the smaller values and the larger values can be interleaved freely as long as each group keeps an order that builds its own subtree, so ways(list) = C(L + R, L) × ways(smaller) × ways(larger). Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).
Input
The first line contains N. The second line contains a permutation of 1..N, the insertion order.
Output
Print the number of other orderings that build the same BST, modulo 1000000007.
Constraints
1 <= N <= 1000; the values are a permutation of 1..N
Example input
5 3 4 5 1 2
Example output
5
Explanation
The order 3 4 5 1 2 builds a tree with root 3, left part 1 → 2 and right part 4 → 5. The two parts can be interleaved in C(4, 2) = 6 ways, and 5 of them differ from the original, so the answer is 5.