Merging trees
Time limit1sMemory limit512 MB
Given a left-handed and a right-handed ternary tree, find the minimum number of vertices in a ternary tree that is a superposition of both.
- Level
Medium7 of 10
- Topics
- Tree, Dynamic programming, Recursion
- Solved
- No attempts yet
Problem
In computing, trees are drawn upside down: the root sits at the top and the leaves sit at the bottom. A tree is a data structure of vertices connected by edges so that you can walk from any vertex to any other vertex along the edges. In a rooted tree, every edge joins a parent vertex to a child vertex. Exactly one vertex has no parent, and that vertex is the root. Starting at the root and following edges from parent to child, you reach every other vertex of the tree.
In a ternary tree, each vertex takes up to three children, called left, center, and right. A left-handed ternary tree is a rooted ternary tree in which no vertex has a right child. A right-handed ternary tree is a rooted ternary tree in which no vertex has a left child. The root of a ternary tree is always a center vertex. The figure below shows a left-handed tree and a right-handed tree.

A superposition of a left-handed tree and a right-handed tree is a ternary tree that meets two conditions. First, the root of is the root of , or the root of , or the two roots laid on top of each other. Second, contains the structure of both trees. The figure below shows a few trees built by superposing the left-handed tree and the right-handed tree above.

In figure (a) the root is vertex of the right-handed tree, and the vertex pairs and are superposed. In figure (b) the root is vertex of the left-handed tree, and the pairs , , are superposed. In figure (c) the root is again vertex of the left-handed tree, and the pair is superposed.
You are given a left-handed tree and a right-handed tree. Find the smallest number of vertices a ternary tree needs in order to be a superposition of the two given trees.
Input
The first line contains an integer , the number of vertices of the left-handed tree. Vertices of this tree are numbered from to , and vertex is the root. Each of the next lines contains three integers , , , meaning that the left child of vertex is and its center child is .
The next line contains an integer , the number of vertices of the right-handed tree. Vertices of this tree are numbered from to , and vertex is the root. Each of the next lines contains three integers , , , meaning that the center child of vertex is and its right child is .
The value means that the child in that slot does not exist. The lines describing vertices do not arrive in numerical order.
Constraints
Output
Print, on one line, the smallest number of vertices of a tree that is a superposition of the two trees given in the input.