#P12355. 「HCOI-R2」巡回演出
「HCOI-R2」巡回演出
Description
The country of HCOI consists of cities, which is abstracted as a rooted tree with nodes, where the capital is the root . Little A plans to start from and traverse all cities for a performance.
Specifically, let be Little A’s current position, and define a sequence as follows:
- Initially, and .
- If has unvisited children, arbitrarily choose one child , append to the end of , and move to .
- If no such exists: If , the performance ends. Otherwise, move to 's parent.
The final sequence is called a traversal method of . Different choices of children yield multiple traversal methods. Note that traversal methods are essentially DFS orders of .
Little A's assistant provides a fee table . The revenue of the tour is defined as:
- For , Little A traverses the simple path on (excluding , including ).
- Each time a node is visited, if it is the -th time of arrival, Little A receives gold coins as payment.
- is the total number of gold coins Little A collects.
The assistant also provides the traversal method for this performance. Little A tree is defined as valid if and only if is one of its traversal methods. You need to compute the sum of over all distinct valid trees , modulo .
Two trees and are considered distinct if they have different roots or there exists an edge present in one tree but not the other.
Input Format
Each single test case has multiple sets of test data.
The first line contains a positive integer representing the number of test cases. For each test case:
The first line contains a positive integer , indicating the number of cities in HCOI.
The second line contains positive integers , representing the traversal method of A’s performance.
The third line contains non-negative integers , representing the fee table for the performance.
Output Format
For each test case, output a single line of integer representing the sum of all valid 's modulo .
7
2
1 2
1
3
1 2 3
1 2
4
1 2 3 4
1 2 3
5
1 3 5 2 4
1 3 2 1
6
6 2 3 4 1 5
3 2 4 7 4
7
1 3 2 4 5 6 7
12 32 84 27 83 11
8
1 7 3 2 8 4 6 5
11 45 14 19 19 8 10
2
10
42
182
1240
41336
124348
2
9
1 2 3 4 5 6 7 8 9
18 48 72 49 83 59 74 80
12
1 12 2 4 3 6 5 7 8 9 11 10
120 938 283 920 462 748 932 784 178 904 442
787978
522215784
1
4
1 2 3 4
1 0 0
20
Hint
Constraints
This problem uses subtasks.
| Subtask | Special Property | Score | ||
|---|---|---|---|---|
| A | ||||
| None | ||||
| B | ||||
| None | ||||
| B | ||||
| None | ||||
- Special Property A: For all , .
- Special Property B: , and for all , .
For all test cases, it is guaranteed that , , , , is a permutation of .
京公网安备 11011102002149号