In-order
Time limit1sMemory limit1024 MB
Count the distinct in-order traversals of binary trees matching given pre-order, post-order, and partial in-order lists, modulo 999999937.
- Level
Hard8 of 10
- Topics
- Tree, Divide and conquer, Combinatorics
- Solved
- No attempts yet
Problem
The opening ceremony for the Olympic Games will take place on the river with teams on boats. The layout of the athletes on top of the boat has been designed in a very specific way: for each team, the athletes (numbered from to ) are arranged as a binary tree.
The organiser has also designed the pre-order traversal, post-order traversal, and a (possibly empty) consecutive part of the in-order traversal of the binary tree that each team must follow.
Now, so that each team can have a distinct tree layout, calculate the number of different possible in-order traversals, , modulo the prime number .
Input
The input consists of four lines. The first line contains the number . Each of the next three lines contains space-separated integers.
The second line contains , where is the number of the th athlete in pre-order traversal.
The third line contains , where is the number of the th athlete in post-order traversal.
The fourth line contains , where is the number of the th athlete in in-order traversal, or if the organiser did not specify that athlete.
Output
The output is a single line containing a single integer , the only integer such that and is divisible by .
Constraints
- There exists at least one binary tree with such pre-order, post-order, and in-order traversals.
- The indices for which form a (possibly empty) sub-interval of . In other words, if and both and are positive, then all of are positive.