#P8260. [CTS2022] 燃烧的呐球

[CTS2022] 燃烧的呐球

Background

Warning: Abusing this problem to hack the judge will result in an account ban.

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 in 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(xi,xj)+D(xj,xi)+D(yi,yj)+D(yj,yi)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 node 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 of the minimum spanning tree.

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

7

Hint

Explanation of the sample:

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 means: the index of the first ordered pair, the index of the second ordered pair, and the edge weight. The total weight is 77.

Constraints:

For 10%10\% of the testdata, 1n,m10001\le n,m\le 1000.

For another 10%10\% of the testdata, 1m2×1041\le m\le 2\times 10^4.

For another 10%10\% of the testdata, 1m5×1041\le m\le 5\times 10^4.

For another 20%20\% of the testdata, m=n2m=n^2, and all ordered pairs are distinct.

For another 10%10\% of the testdata, for all i=2ni=2\cdots n, fi=i1f_i=i-1.

For another 10%10\% of the testdata, for all i=2ni=2\cdots n, fi=1f_i=1.

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

Translated by ChatGPT 5