Drawing Binary Trees
Time limit1sMemory limit512 MB
Count the x-coordinate assignments for a binary tree's nodes in [1, V] that keep the left-below, right-above ordering and match the fixed values in A, modulo 444449.
- Level
Medium7 of 10
- Topics
- Tree, Dynamic programming, Combinatorics
- Solved
- No attempts yet
Problem
Bert has recently become fascinated with binary trees. For a tree to be a binary tree, each node may have at most 2 children. For convenience, the nodes of a binary tree are numbered 1 through . The left child of node is written , and the right child is written . If a node has no child on that side, the value is 0.
The tree below has , , and . Its root is node 1.

Bert likes to draw binary trees. He first fixes an integer that is large enough, then draws the tree in several ways by the rules below. Let the integer coordinates of node be .
- Choose so that .
- If node is the root, then .
- If node is the parent of node , then .
- If a non-root node is the left child of node (that is, ), then must hold. Also, must hold for every child and descendant of .
- If a non-root node is the right child of node (that is, ), then must hold. Also, must hold for every child and descendant of .
When coordinates satisfy all the rules above, the binary tree can be drawn. Two drawings are different if any node has a different coordinate in them. Under these rules, every node has the same coordinate in every drawing.
For the example above with , the tree can be drawn in 4 different ways, as shown below.

Given any binary tree, Bert wondered how many different drawings follow all of the rules above. Alice saw this and called that problem too easy, so she gave him a new one.
- If the coordinates of some of the nodes (possibly none, possibly all) are fixed, how many different drawings are possible when the rules above are followed?
- Specifically, an integer array is given. If , the coordinate of node is not fixed. If , then the coordinate of node must be exactly .
For example, if , the tree can be drawn in the 3 leftmost ways among the 4 drawings above, which are the ones with . For the same tree with , there is no valid drawing. The tree can be drawn in 4 ways as shown above, but none of them has .
Given , , and three integer arrays , , and , count the number of ways to draw the binary tree that satisfy Alice's conditions.
Input
The first line contains the number of test cases .
The first line of each test case contains and , separated by a space. The second line contains the array , the third line contains the array , and the fourth line contains the array . Each array is given as integers separated by spaces.
Output
For each test case, print the answer on its own line. The answer can be very large, so print the remainder when it is divided by .
Constraints
- For every with :
- The input binary tree has nodes and edges, has a unique root, and contains no cycles. This is guaranteed.