QOJ.ac

QOJ

Time Limit: 3 s Memory Limit: 512 MB Total points: 100

#14179. 2stmo

Statistics

Given a rooted tree with $n$ vertices, labeled $1, \dots, n$, where $1$ is the root and $f_2, \dots, f_n$ denote the parents of $2, \dots, n$ respectively.

Given $m$ pairs of integers $a_1, b_1, \dots, a_m, b_m$, you need to construct a permutation $p_1, \dots, p_m$ of $1, \dots, m$ such that the cost of the permutation does not exceed $4 \times 10^9$.

The cost of the permutation is defined as:

$$|S(a_{p_1})|+|S(b_{p_1})|+\sum\limits_{i=2}^m |S(a_{p_{i-1}})\oplus S(a_{p_i})|+|S(b_{p_{i-1}})\oplus S(b_{p_i})|$$

where $S(x)$ is the set of vertices in the subtree rooted at $x$, $|A|$ is the number of elements in set $A$, and $A\oplus B$ is the symmetric difference of sets $A$ and $B$ (i.e., the set of elements that appear in exactly one of $A$ or $B$).

Input

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

The second line contains $n-1$ integers $f_2, \dots, f_n$.

The next $m$ lines each contain two integers representing $a_i, b_i$ for $i=1, \dots, m$.

Output

Output $m$ lines, each containing an integer, representing $p_1, \dots, p_m$ in order.

Examples

Input 1

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

Output 1

2
3
1

Subtasks

Idea: nzhtl1477, Solution: ccz181078, Code: ccz181078, Data: ccz181078

For $25\%$ of the data, $n, m \le 10^4$.

For $50\%$ of the data, $n, m \le 2 \times 10^5$.

For $75\%$ of the data, $n, m \le 5 \times 10^5$.

For $100\%$ of the data, $1 \le n, m \le 10^6$, $1 \le f_i \le i-1$, and $1 \le a_i, b_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.