Infinite Trees
Time limit2sMemory limit512 MB
Given two possibly infinite trees defined by node-to-children mappings, decide whether their roots have the same ordered structure, where recursive nodes make the unfolding infinite and require comparing regular trees.
Problem
Type checking is the process of verifying that a program satisfies the typing rules of a programming language. In some languages this is very difficult, and even deciding whether two types are equal can be tricky.
In this problem a type is a tree made of nodes. Each node has zero or more child nodes, and the children correspond to component types. Here is an example of such a tree.

Figure 1: a simple finite tree. The root is node 0 and its children are nodes 1 and 2. Node 1 has no children, and node 2 has one child, node 3.
Types are allowed to be recursive. A node can have any node as a child, including its parent and even itself. The result is an infinite tree.

Figure 2: an infinite tree. Node 0 has node 2 as a child, node 2 has node 0 as a child, node 0 has node 2 as a child again, and so on. The tree goes on forever, so the picture was cut off to fit on the page.
You are given two trees that may be infinite. Decide whether they have the same structure. Nodes and have the same structure when both of these hold.
- They have the same number of children.
- For every child index , the -th child of and the -th child of have the same structure.
Two trees have the same structure when their root nodes have the same structure.
Input
The input holds a sequence of problems. The first line of each problem has two space separated integers and , the number of nodes in the two trees ().
The next lines describe the first tree. Counting from 0, line holds space separated integers describing node . The first integer is , the number of children of node (, and the sum of over one tree is at most ). The remaining integers are the children of node , listed in order. The next lines describe the second tree the same way. The root of each tree is node 0.
A blank line follows each problem. The end of the input is a line with two zeroes, which you do not process.
Output
For each problem print YES if the two trees have the same structure, or NO if they do not. Print one answer per line, in uppercase.
Hint
In the first problem of the first example the first tree is the tree of Figure 1, and the second tree is its mirror image. The order of the children matters, so the two structures differ.
Figure 2 shows the first tree of the second problem in the first example. The second tree uses more nodes but has the same structure.