QOJ.ac

QOJ

Time Limit: 4 s Memory Limit: 2048 MB Total points: 100

#10163. Tree Quiz

统计

你的朋友想考考你。给定一棵有 $n$ 个节点的有根树,节点编号从 1 到 $n$。对于每个节点 $i$,其父节点为 $p_i$,根节点(没有父节点的节点)除外,其 $p_i = 0$。如果 $u = v$,或者节点 $u$ 是节点 $v$ 的父节点的祖先(如果存在),则称节点 $u$ 是节点 $v$ 的祖先。

如果节点 $z$ 同时是节点 $x$ 和 $y$ 的祖先,则称节点 $z$ 是节点 $x$ 和 $y$ 的公共祖先。如果节点 $z$ 是节点 $x$ 和 $y$ 的公共祖先,且 $x$ 和 $y$ 的任意公共祖先也都是 $z$ 的祖先,则称节点 $z$ 是节点 $x$ 和 $y$ 的最近公共祖先。我们将节点 $x$ 和 $y$ 的最近公共祖先记为 $\text{LCA}(x, y)$。特别地,$\text{LCA}(x, x) = x$。

你的朋友想要运行以下伪代码:

let L be an empty array
for x = 1 to n
for y = 1 to n
append ((x - 1) * n * n + (LCA(x, y) - 1) * n + (y - 1)) to L
sort L in non-decreasing order

你的朋友有 $q$ 个问题,编号从 1 到 $q$。在第 $j$ 个问题中,给定一个整数 $k_j$,要求找出数组 $L$ 中的第 $k_j$ 个元素。注意 $L$ 的下标从 1 开始,因此下标范围为 $1$ 到 $n^2$(包含边界)。为了通过测试,你必须回答所有问题。

输入格式

第一行包含两个整数 $n$ 和 $q$ ($1 \le n \le 100\,000$; $1 \le q \le 100\,000$)。第二行包含 $n$ 个整数 $p_1, p_2, \dots, p_n$ ($0 \le p_i \le n$ 对于所有 $i$)。保证给定的值构成一棵有根树。接下来的 $q$ 行,每行包含一个整数。第 $j$ 行包含 $k_j$ ($1 \le k_j \le n^2$)。

输出格式

对于每个问题,按顺序输出一个整数,表示该问题的答案。

样例

输入 1

5 3
3 0 2 2 3
1
18
25

输出 1

0
82
124

说明

输入中的树如图 K.1 所示。

图 K.1:样例输入 #1 中的树示意图。

数组 $L$ 的元素为 $(0, 6, 8, 12, 14, 30, 31, 32, 33, 34, 56, 58, 60, 62, 64, 80, 81, 82, 84, 93, 106, 108, 110, 112, 124)$。

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.