atcoder#ABC255F. [ABC255F] Pre-order and In-order

[ABC255F] Pre-order and In-order

Score : 500500 points

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

6
1 3 5 6 4 2
3 5 1 4 6 2
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.

2
2 1
1 2
-1

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