Arboriculture
Time limit1sMemory limit1024 MB
Match each of N target trees to a distinct ordered tree and cut branches so each becomes its target, minimizing the total number of cuts.
- Level
Medium7 of 10
- Topics
- Tree, Dynamic programming, Graph
- Solved
- No attempts yet
Problem
In preparation for the Swedish Coding Cup Finals, the organizing committee is decorating the hall for the award ceremony with beautiful juniper trees. They have designed an arrangement of trees, each with a specific look. As the resident arborist of the competition, it is your job to fix the trees.
You ordered trees, and the shipment arrived a minute ago. You may not be able to pick trees that match the arrangement exactly. In that case, you must cut off some branches on some trees to change their looks into those required by the arrangement. The contest has just started, so you need to fix the trees right now, before the award ceremony.
Formally, a tree consists of a root, from which a number of branches (possibly none) extend. Each branch ends at a point called a vertex, from which any number of new branches can extend. Two trees look the same if they have the same structure of branches and vertices. The order in which branches grow from a vertex does not matter.
To change the layout of a tree, you can use your trusty lopper to cut off branches that grow from a vertex, one branch at a time. Branches can be cut from any part of the tree. Cutting a branch makes the whole subtree below it fall off. You want to finish as fast as possible. If you choose of the trees and cut them optimally, how many cuts do you need in total?
Input
The first line contains two integers (), the number of trees in the arrangement, and (), the number of trees you ordered.
Then tree descriptions follow. First come the trees of the arrangement, followed by the ordered trees. A tree description starts with an integer , the number of branches. The next line contains integers , where . Each means that there is a branch between vertex and vertex . If a branch grows from the root, this number is .
There are at most branches in total among the trees. It is guaranteed that the trees can be transformed in the described manner.
Output
Output a single integer: the minimum number of edges you must cut to transform the layouts of of the ordered trees into the layouts of the trees in the arrangement.
Hint
In the first sample, three trees are ordered and two trees need to be constructed. The second ordered tree exactly matches the first tree in the arrangement, so it can be chosen without any cuts. The third ordered tree is similar to the second tree in the arrangement, except it has an extra branch from the root. Thus, only one cut is needed to transform it.