#P16222. [ECUSTPC 2025] 荷塘月色
[ECUSTPC 2025] 荷塘月色
Problem Description
Maddy encountered many blooming lotus flowers, but there was also something eerie among them...
In this lotus pond, there is a tree with nodes, which is an undirected, acyclic, connected graph formed by edges.
Each node () has a weight , and a -pair on a tree is defined as follows:
- , and and are integers representing nodes on the tree.
- Let the weights of the nodes on the path from node to node form a multiset . Note that and are also included on the path.
- It is required that , i.e. the greatest common divisor of the elements in equals the minimum value in , and both are .
Maddy now randomly chooses two distinct nodes on the tree. If there exists a such that is a -pair, then she will get lanterns.
Please help Maddy compute the expected number of lanterns she gets. Output , which is the value of the expectation taken modulo . See the Hint for the specific output requirement.
Input Format
The first line contains an integer (), denoting the number of test cases.
For each test case, the first line contains an integer (), denoting the number of vertices in the graph.
Then follow lines, each containing two integers and (), indicating that there is an edge between and in the tree .
Then one line contains integers (), representing the weights of the nodes in the tree.
It is guaranteed that over all testdata, and that the graph in each test case forms a tree.
Output Format
For each test case, output one line with an integer , representing the expected number of lanterns Maddy gets modulo .
1
6
1 2
1 3
2 4
2 5
3 6
6 2 3 4 2 1
332748119
Hint
Explanation for Sample 1
The given tree has 6 nodes, with edges
The weights are $a_1 = 6, a_2 = 2, a_3 = 3, a_4 = 4, a_5 = 2, a_6 = 1.$
We enumerate all pairs of nodes, and check whether equals for the multiset of weights on the path.
For example:
- Pair : the path is , , , so it belongs to .
- Pair : the path is , , , so it belongs to .
- Pair : the path is , , , so it belongs to .
- Pair : the path is , , , which does not satisfy the condition.
The final counts are:
: 5 pairs ,
: 6 pairs ,
: 1 pair ,
: 0 pairs.
Thus the expected number of lanterns is
$$\frac{5 \times 1 + 6 \times 2 + 1 \times 3 + 0 \times 4 + 0 \times 5 + 0 \times 6}{15} = \frac{4}{3}.$$Taking it modulo gives the answer .
Hint
It can be proven that the answer of this problem is a rational number. Let it be where and are coprime. The number you output, , must satisfy and
It can be proven that such an must exist under the meaning of this problem.
Translated by ChatGPT 5