#abc255f. F - Pre-order and In-order

F - Pre-order and In-order

Score : 500500 points

问题陈述

考虑一个具有 NN 个顶点的 二叉树,顶点编号为 1,2,,N1, 2, \ldots, N。此处,二叉树是一个根树,其中每个顶点最多有两个子节点。具体来说,二叉树中的每个顶点至多有一个 左孩子 和至多有一个 右孩子

确定是否存在一棵以顶点 11 为根的二叉树满足以下条件,并在存在时给出这样的树。

  • 该树按 前序遍历 的深度优先遍历序列为 (P1,P2,,PN)(P_1, P_2, \ldots, P_N)
  • 该树按 中序遍历 的深度优先遍历序列为 (I1,I2,,IN)(I_1, I_2, \ldots, I_N)

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

Consider a binary tree with NN vertices numbered 1,2,,N1, 2, \ldots, N. Here, a binary tree is a rooted tree where each vertex has at most two children. Specifically, each vertex in a binary tree has at most one left child and at most one right child.

Determine whether there exists a binary tree rooted at Vertex 11 satisfying the conditions below, and present such a tree if it exists.

  • The depth-first traversal of the tree in pre-order is (P1,P2,,PN)(P_1, P_2, \ldots, P_N).
  • The depth-first traversal of the tree in in-order is (I1,I2,,IN)(I_1, I_2, \ldots, I_N).

Constraints

  • 2N2×1052 \leq N \leq 2 \times 10^5
  • NN is an integer.
  • (P1,P2,,PN)(P_1, P_2, \ldots, P_N) is a permutation of (1,2,,N)(1, 2, \ldots, N).
  • (I1,I2,,IN)(I_1, I_2, \ldots, I_N) is a permutation of (1,2,,N)(1, 2, \ldots, N).

Input

Input is given from Standard Input in the following format:

NN

P1P_1 P2P_2 \ldots PNP_N

I1I_1 I2I_2 \ldots INI_N

Output

If there is no binary tree rooted at Vertex 11 satisfying the conditions in Problem Statement, print 1-1.

Otherwise, print one such tree in NN lines as follows. For each i=1,2,,Ni = 1, 2, \ldots, N, the ii-th line should contain LiL_i and RiR_i, the indices of the left and right children of Vertex ii, respectively. Here, if Vertex ii has no left (right) child, LiL_i (RiR_i) should be 00.

If there are multiple binary trees rooted at Vertex 11 satisfying the conditions, any of them will be accepted.

L1L_1 R1R_1

L2L_2 R2R_2

\vdots

LNL_N RNR_N

Sample Input 1

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

Sample Output 1

3 6
0 0
0 5
0 0
0 0
4 2

The binary tree rooted at Vertex 11 shown in the following image satisfies the conditions.

Sample Input 2

2
2 1
1 2

Sample Output 2

-1

No binary tree rooted at Vertex 11 satisfies the conditions, so 1-1 should be printed.

update @ 2024/3/10 10:52:11