Under construction

Still being built. Things may change

Binary Trees

Time limit1sMemory limit1024 MB

Summary
Given two rooted binary trees on N vertices, output at most N subtree-move operations that turn the first tree into one isomorphic to the second.
Level

Hard9 of 10

Topics
Tree, Greedy, Simulation, Recursion
Solved
No attempts yet

Statement

Yesterday Vadim found a binary tree aa rooted at 0 with NN vertices on the road. His favorite, however, is a binary tree bb rooted at 0 with NN vertices. So he decided to turn aa into bb with the following operation:

  • Pick any vertex vv other than the root. Its subtree, including vv itself, is reattached below a vertex uu that does not belong to the chosen subtree. The result must be a binary tree rooted at 0.

Vadim is sure that this operation can turn the tree he found into a tree isomorphic to his favorite, using at most NN operations. Help him find the sequence of operations.

A binary tree is a tree in which each vertex is an ancestor of at most 2 other vertices, and the root has no ancestor.

Two rooted binary trees are isomorphic if one of the following holds:

  1. Both trees consist of a single vertex.
  2. The roots have the same number of children, the subtree of each child of the first tree is isomorphic to the subtree of some child of the second tree, and the subtree of each child of the second tree is isomorphic to the subtree of some child of the first tree.

Input

The first line contains an integer NN (2≤N≤1032 \le N \le 10^3), the number of vertices in both the found tree and the favorite tree.

The second line contains N−1N-1 integers paipa_i, the parents of vertices 11 to N−1N-1 in the found tree (0≤pai≤N−10 \le pa_i \le N-1).

The third line contains N−1N-1 integers pbipb_i, the parents of vertices 11 to N−1N-1 in the favorite tree (0≤pbi≤N−10 \le pb_i \le N-1).

It is guaranteed that both trees are binary.

Output

On the first line, print the number of operations MM (0≤M≤N0 \le M \le N).

Then print MM lines, each with two integers vv and uu: the root of the chosen subtree and the vertex it is reattached to during that operation (1≤v≤N−11 \le v \le N-1, 0≤u≤N−10 \le u \le N-1). Vertex uu cannot lie in the subtree of vv. The tree after each operation must be binary.

An answer is guaranteed to exist. If several answers exist, print any of them.

Examples2

  1. Example 1

    Input
    4
    0 0 1
    0 1 2
    
    Expected output
    1
    2 3
    
  2. Example 2

    Input
    4
    2 0 0
    0 3 0
    
    Expected output
    0