Tree Similarity
Time limit3sMemory limit128 MB
Given two ordered rooted trees, find the minimum number of node relabel, delete, and insert operations to turn the first tree into the second.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Tree, DFS, Recursion
- Solved
- No attempts yet
Problem
You are given two labeled, ordered, rooted trees and (each node holds a number). Write a program that computes the distance between and , defined as the minimum number of operations needed to make equal to .
There are three operations:
- Change the number written on one node of .
- Delete one non-root node of .
- Insert one node somewhere below the root of .
Because and are ordered trees, if a non-leaf node has children, those children are ordered from the 1st to the -th.
Two trees and are equal if their roots hold the same number and have the same number of children, and, for every , the subtree rooted at the -th child of is equal to the subtree rooted at the -th child of ().
Deletion and insertion are defined as follows. Suppose a non-root node has children, its parent is , and is the -th child of . When is deleted, its children move up into 's place: the first child of becomes the -th child of , the second becomes the -th child of , and so on. The children of at positions keep their order, while every child at position is shifted to become the -th child of .
To insert a non-root node , first choose the node that will become its parent. Then pick a contiguous subsequence of 's children, make them the children of , and place in their position. When inserting , you may write any number on it.
You may not delete the root of or insert a new node above the root. However, you may change the number written on the root.
(For example, one may delete a node , or take the 2nd through 4th children of , group them as the children of a new node , and insert below .)
Input
The first line contains the node counts and of the two trees and ().
The next lines describe . Nodes are numbered from to ; the -th of these lines describes node . Each line gives the number written on that node and its number of children, followed by the indices of its children in order (indices are 0-based).
The following lines describe in the same format.
Every number written on a node is a non-negative integer, and the root of each tree is the node that is not a child of any other node.
Output
Print the minimum number of operations needed to make equal to .