QOJ.ac

QOJ

時間限制: 1.0 s 記憶體限制: 64 MB 總分: 100 可 Hack ✓

#6790. 二叉树还原

统计

给定一棵二叉树的两个深度优先搜索(DFS)序列,你能找到一棵同时满足这两个 DFS 序列的二叉树吗?

回想一下,二叉树是指每个顶点最多有两个子节点的树,而深度优先搜索是一种树的遍历方法,它从根节点开始,在回溯之前尽可能深地沿着每个分支进行探索。

输入格式

输入包含多组测试数据。第一行包含一个整数 $T$,表示测试数据的组数。对于每组测试数据:

第一行包含一个整数 $n$ ($1 \le n \le 10^5$),表示二叉树中顶点的数量。

第二行包含 $n$ 个整数 $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n, \forall 1 \le i < j \le n, a_i \neq a_j$),表示二叉树的第一个 DFS 序列。

第三行包含 $n$ 个整数 $b_1, b_2, \dots, b_n$ ($1 \le b_i \le n, \forall 1 \le i < j \le n, b_i \neq b_j$),表示二叉树的第二个 DFS 序列。

保证所有测试数据的 $n$ 之和不超过 $10^6$,且至少存在一棵可能的二叉树。

我们提醒您,本题涉及大量的输入输出,建议使用较快的 I/O 方法。例如,在 C++ 中可以使用 scanf/printf 代替 cin/cout

输出格式

对于每组测试数据,输出一行,包含 $n$ 个由空格分隔的整数。第 $i$ 个整数表示在满足这两个 DFS 序列的二叉树中,第 $i$ 个顶点的父节点。如果第 $i$ 个顶点是二叉树的根,则输出 $0$ 作为其父节点。如果存在多个有效的答案,你可以输出其中任意一个。

请注意,不要在每行末尾打印多余的空格,否则你的程序可能会因为本题采用特殊判题(special judge)而得到“答案错误”的判决。

样例

样例输入 1

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

样例输出 1

3 4 0 3 4 1
0 1 2

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.