Binary Trees
Time limit1sMemory limit1024 MB
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 rooted at 0 with vertices on the road. His favorite, however, is a binary tree rooted at 0 with vertices. So he decided to turn into with the following operation:
- Pick any vertex other than the root. Its subtree, including itself, is reattached below a vertex 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 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:
- Both trees consist of a single vertex.
- 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 (), the number of vertices in both the found tree and the favorite tree.
The second line contains integers , the parents of vertices to in the found tree ().
The third line contains integers , the parents of vertices to in the favorite tree ().
It is guaranteed that both trees are binary.
Output
On the first line, print the number of operations ().
Then print lines, each with two integers and : the root of the chosen subtree and the vertex it is reattached to during that operation (, ). Vertex cannot lie in the subtree of . The tree after each operation must be binary.
An answer is guaranteed to exist. If several answers exist, print any of them.