QOJ.ac

QOJ

時間限制: 10 s 記憶體限制: 2048 MB 總分: 100 难度: [顯示]

#4408. Burning Na-Ball

统计

Given a rooted tree with $n$ vertices and $m$ pairs $(x_i, y_i)$, where $x_i$ and $y_i$ are vertices of the tree.

For vertices $a$ and $b$ in the tree, define $D(a, b)$ as the number of vertices that are in the subtree rooted at $a$ but not in the subtree rooted at $b$.

You need to find the minimum spanning tree of a complete graph where the vertices are these $m$ pairs, and the weight of the edge between $(x_i, y_i)$ and $(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

The first line contains two integers $n$ and $m$.

The next line contains $n-1$ integers, where the $i$-th integer represents the parent $f_{i+1}$ of node $i+1$. It is guaranteed that $f_{i+1} < i+1$.

The next $m$ lines each contain two integers $x_i$ and $y_i$, representing a given pair.

Output

Output a single integer representing the sum of the edge weights of the minimum spanning tree.

Examples

Input 1

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

Output 1

7

Note 1

The minimum spanning tree contains edges $(1, 4, 1), (2, 3, 3), (2, 4, 3)$, where the triplet represents the index of the first pair, the index of the second pair, and the edge weight. The sum of the edge weights is $7$.

Subtasks

For $10\%$ of the data, $1 \le n, m \le 1000$.

For another $10\%$ of the data, $1 \le m \le 2 \times 10^4$.

For another $10\%$ of the data, $1 \le m \le 5 \times 10^4$.

For another $20\%$ of the data, $m = n^2$, and all pairs are distinct.

For another $10\%$ of the data, $f_i = i-1$ for all $i = 2, \dots, n$.

For another $10\%$ of the data, $f_i = 1$ for all $i = 2, \dots, n$.

For $100\%$ of the data, $1 \le n \le 10^6, 1 \le m \le 10^5$. For all $i = 1, 2, \dots, n-1$, $1 \le f_{i+1} < i+1$. For all $i = 1, 2, \dots, m$, $1 \le x_i, y_i \le n$.

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.