#P17438. 「LWLV Round 1」天气先生
「LWLV Round 1」天气先生
Background
Maybe the sun won't shine
Maybe the rain won't fall
But maybe our love will find a way
And rise above it all
Maybe there comes a day
When all of the skies turn grey
Maybe today our love can fly high
You and I will soar
Problem Description
There is a tree with nodes, where the root is . Each node has a node weight which is .
We define the weather value of some DFS order of this tree as:
$$\left|w_{s_1}-w_{s_2}\right|+\left|w_{s_2}-w_{s_3}\right|+\cdots+\left|w_{s_{n-1}}-w_{s_n}\right|$$Please find the sum of the weather values over all DFS orders of the tree .
:::info[DFS order] For a tree rooted at , its DFS order refers to a sequence of length formed by the order in which nodes are visited (entered) when traversing the whole tree starting from the root, following the rules of depth-first search (DFS).
In a standard DFS process, the following principles are followed:
- Start from the root node. Each time a node is visited, immediately recursively visit one of its unvisited children.
- Only after all children of the current node have been visited will the traversal backtrack to its parent.
- During the whole traversal, each node is visited (recorded into the sequence) exactly once. :::
:::info[All DFS orders] In a typical DFS algorithm, when a node has multiple children, the algorithm may choose any child as the next one to visit. This freedom in choosing the visiting order of children means that the same tree may generate many different DFS orders.
“All DFS orders” means: during the traversal of this tree, enumerate all permutations of the children of each node as the visiting order, and take the set of all valid DFS traversal sequences generated in this way. :::
Output the answer modulo .
Input Format
The first line contains a positive integer , the number of nodes.
The second line contains integers , the node weights.
The next lines each contain two positive integers , indicating that there is an edge connecting and .
Output Format
One line, the result of the answer modulo .
4
0 1 0 1
1 2
1 3
3 4
4
Hint
Sample Explanation
There are two DFS orders: . They correspond to node-weight sequences , and the answer is .
Constraints
| Subtask ID | Special Property | Score | |
|---|---|---|---|
| None | |||
| ^ | All leaves have the same weight | ||
| None |
For of the testdata, it is guaranteed that 。
Translated by ChatGPT 5