Cartesian Trees
Time limit3sMemory limit256 MB
Count the number of distinct Cartesian trees (BST over keys 1..n, max-heap over given priorities) modulo 1e9+7, summed over test cases with total n up to 2e5.
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Combinatorics, Stack
- Solved
- No attempts yet
Problem
Recently, at a university lecture, Vasya learned what a Cartesian tree is. A Cartesian tree is a binary tree where each node stores two values: a key and a priority. It is a search tree over the set of keys and a max-heap over the priorities, that is:
- the key of any node in the left subtree of node is less than the key of node ;
- the key of any node in the right subtree of node is greater than the key of node ;
- the priorities of the children of node are not greater than the priority of node itself.
On a test, Vasya was given the following problem: given pairs of the form (key, value), the -th of which is , find how many ways there are to build a Cartesian tree using the number as the key of node and as its priority. Since this number can be quite large, find its remainder modulo .
Two Cartesian trees are considered different if they have different roots, or if there is a node that has different ancestors in these trees.
Input
The first line contains a single positive integer : the number of test cases in the input. The descriptions of the test cases follow.
The description of each test case consists of two lines. The first line contains a single integer (): the number of nodes in the tree. The second line contains integers (): the priority of the -th node of the tree.
The sum of over all test cases does not exceed .
Output
For each test case, output on a separate line a single integer: the number of distinct Cartesian trees that can be built on the given set of priorities, modulo .