#P8336. [Ynoi2004] 2stmst
[Ynoi2004] 2stmst
Problem Description
You are given a rooted tree with vertices, and ordered pairs , where are vertices of the tree.
For vertices of the tree, define as: the number of vertices that are in the subtree rooted at , but not in the subtree rooted at .
You need to find the minimum spanning tree of the complete graph whose vertices are these ordered pairs. The edge weight between and 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 .
The next line contains integers. The -th integer denotes the parent of the node with index , and it is guaranteed that .
Then follow lines. The -th line contains two integers , 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( ), Rainbow_qwq( ), Code: ccz181078&djq_cpp&Rainbow_qwq, Data: ccz181078.
Sample explanation:
The minimum spanning tree contains edges . 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 .
Constraints:
For of the testdata, , . For any , . For any , .
Translated by ChatGPT 5