#P9866. C. Rotation
C. Rotation
C. Rotation
Problem Description
There is a binary tree with the root at vertex , and each vertex in the tree has a weight . You can perform the following two operations:
- If vertex has left child and right child , and its left child has a right child , then you can perform a "rotation" on these four vertices. Let , and then let .
- If vertex has left child and right child , and its right child has a left child , then you can perform a "rotation" on these four vertices. Let , and then let . Find the number of different point weight arrays that can be obtained by performing a series of operations, modulo .
Input
The input consists of multiple test cases. The first line contains a single integer () - the number of test cases. Description of the test cases follows. The first line of each test case contains one integer () - the number of vertices in the tree. The second line contains integers () - the point weights. Each of the following lines contains two integers () - the left child and right child of vertex . If a child does not exist, it is represented by . It's guaranteed that .
Output
For each test case, print a single integer - the number of different point weight arrays that can be obtained by performing a series of operations, modulo .
Sample Input
2
4
1 2 2 1
2 3
0 4
0 0
0 0
8
1 2 3 4 5 6 7 8
2 3
4 5
6 7
0 0
0 0
0 8
0 0
0 0
Sample Output
2
5040
Source
2023“钉耙编程”中国大学生算法设计超级联赛(7)