#GL0000262. Gây bất ngờ! (Surprise me!)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Gây bất ngờ! (Surprise me!)
Surprise me!
Source: Codeforces
Version: Phuoc Hung OJ Extended
Problem Statement
Leha and Noora play a game on a tree with vertices numbered from to . A tree is a connected undirected graph without cycles. Each vertex carries an integer . The numbers form a permutation of : every integer occurs exactly once.
Noora chooses a vertex uniformly at random from all vertices. Leha then uniformly chooses a vertex among the remaining vertices, so . Every ordered pair has the same probability.
The value of this choice is
where is the number of integers with and , and is the number of edges along the unique simple path between the vertices.
Find the expected value of over all ordered pairs. Express the expectation as a reduced fraction . Print modulo , where is the multiplicative inverse of modulo .
Input
- The first line contains an integer , the number of vertices.
- The second line contains exactly integers in vertex order.
- Each of the following lines contains two integers , describing one undirected edge connecting and .
Output
Print a single integer representing the expected value modulo .
Subtasks
- Subtask 1 (20 points): ; for every , with all distinct; for every edge ; the edges form an undirected tree.
- Subtask 2 (30 points): ; for every , with all distinct; for every edge ; the edges form an undirected tree.
- Subtask 3 (50 points): ; for every , with all distinct; for every edge ; the edges form an undirected tree.
Examples
Example 1
Input
3
1 2 3
1 2
2 3
Output
333333338
Explanation
There are ordered pairs. Pairs and each contribute . Pairs and each contribute . Pairs and each contribute . The sum equals , so the expectation is . The modular inverse of is , which gives .
Example 2
Input
5
5 4 3 1 2
3 5
1 2
4 3
2 5
Output
8
Explanation
The edges form the path . The values along the path are . The sum of over the unordered pairs equals ; each unordered pair is counted twice in the ordered sum, so the total is . Dividing by gives the expectation , which is also the modular answer.