#P8336. [Ynoi2004] 2stmst

[Ynoi2004] 2stmst

Problem Description

You are given a rooted tree with nn vertices, and mm ordered pairs (xi,yi)(x_i, y_i), where xi,yix_i, y_i are vertices of the tree.

For vertices a,ba, b of the tree, define D(a,b)D(a, b) as: the number of vertices that are in the subtree rooted at aa, but not in the subtree rooted at bb.

You need to find the minimum spanning tree of the complete graph whose vertices are these ordered pairs. The edge weight between (xi,yi)(x_i, y_i) and (xj,yj)(x_j, y_j) is $D(x_i, x_j) + D(x_j, x_i) + D(y_i, y_j) + D(y_j, y_i)$.

Input Format

The first line contains two integers n,mn, m.

The next line contains n1n - 1 integers. The ii-th integer denotes the parent fi+1f_{i+1} of the node with index i+1i+1, and it is guaranteed that fi+1<i+1f_{i+1} < i + 1.

Then follow mm lines. The ii-th line contains two integers xi,yix_i, y_i, representing a given ordered pair.

Output Format

Output one integer, the sum of edge weights in the minimum spanning tree.

5 4
1 2 3 3
3 5
2 2
5 2
2 5

7

Hint

Idea: nzhtl1477, Solution: ccz181078( O(mlognlogm+nlogn)O(m\log n\log m+n\log n) ), Rainbow_qwq( O(mlogn+n)O(m\log n+n) ), Code: ccz181078&djq_cpp&Rainbow_qwq, Data: ccz181078.

Sample explanation:

The minimum spanning tree contains edges (1,4,1),(2,3,3),(2,4,3)(1,4,1), (2,3,3), (2,4,3). Each triple represents: the index of the first ordered pair, the index of the second ordered pair, and the edge weight. The sum of edge weights is 77.

Constraints:

For 100%100\% of the testdata, 1n1061 \le n \le 10^6, 1m1051 \le m \le 10^5. For any i=1,2,,n1i = 1, 2, \dots, n - 1, 1fi+1<i+11 \le f_{i+1} < i + 1. For any i=1,2,,mi = 1, 2, \dots, m, 1xi,yin1 \le x_i, y_i \le n.

Translated by ChatGPT 5