#P8334. [ZJOI2022] 深搜
[ZJOI2022] 深搜
Problem Description
Kanjou Karen is a girl who likes algorithms. Among many algorithms, she especially likes depth-first search (DFS).
One day, Karen obtained a rooted tree with root . Each node on the tree has a weight .
On a tree, starting from to search for node , if we use depth-first search, it can be described by the following procedure:
- Set the recursion stack to be empty.
- First, push node into the recursion stack.
- Pop the top node from the recursion stack. If this node is , then stop the procedure. Otherwise, if there exists an unvisited direct child, then uniformly at random choose one child and push it into the recursion stack.
- Repeat step 3 until there is no unvisited direct child.
- Push the parent node into the recursion stack and repeat step 3.
- Repeat step 5 until the current node is , and the procedure ends.
We define to be valid if and only if is in the subtree of . Its value is the expected minimum weight among all nodes visited (including and ) during the DFS on the subtree of starting from while searching for .
Karen wants to know, for all valid pairs , the value of . You only need to output the result modulo . Specifically, if the answer in lowest terms is , output .
Input Format
The input contains multiple test cases. The first line contains an integer , the number of test cases.
For each test case, the first line contains two integers , representing the size of the tree and the index of the root.
The next line contains integers , representing the weight of each node.
The next lines each contain two integers , indicating that there is an edge between and .
Output Format
For each test case, output one line containing one integer, representing over all valid pairs modulo .
4
1 1
1
3 3
3 3 4
3 1
3 2
6 1
5 2 4 1 3 6
1 2
1 6
2 3
2 4
4 5
5 1
5 4 3 2 1
1 2
1 3
3 4
3 5
1
16
34
499122202
见附件中的 dfs/dfs_ex2.in
见附件中的 dfs/dfs_ex2.ans
Hint
For all test points, it holds that , , , , .
The detailed limits for each test point are shown in the table below:
| Test Point ID | Special Constraints | ||
|---|---|---|---|
| None | |||
| The tree generation is random | |||
| The tree is a chain | |||
| The degree of the root is | |||
| None |
For test point , the tree is generated as follows: take as the root. For each node , uniformly at random choose a node from as its parent. Then the labels are randomly permuted.
Translated by ChatGPT 5