Spring cleaning
Time limit1sMemory limit128 MB
Given a tree and Q variations that attach extra leaves, find the minimum total length of leaf-pair paths that cover every edge, or -1 if impossible.
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
This tree has nodes numbered from 1 to , connected by edges. The edges have gathered too much dust, so Flóra's mother decided to clean them.
Cleaning the edges of an arbitrary tree is done by repeating the following process. Choose two different leaves (a node is a leaf if it is connected to exactly one other node by an edge), and clean every edge on the shortest path between them. If this path has edges, the cost of cleaning it is .
To avoid harming the leaves, each leaf may be chosen at most once. A tree is clean when all of its edges are cleaned. The cost is the sum of the costs of all cleaned paths.
Flóra thinks the tree is too small and simple, so she imagines variations of it. In the -th variation, she adds a total of extra leaves to the original tree. For each new leaf, she picks a node of the original tree and connects that node to the new leaf with an edge. Some nodes may stop being leaves after this step.
For each of the variations, find the minimum cost required to clean the tree. Each variation starts from the original tree.
Input
The first line contains two integers and .
Each of the next lines contains two integers and , meaning that nodes and are connected by an edge.
Each of the next lines describes one variation. The first integer on the -th line is , followed by integers . Each is the node to which a new leaf is attached. Several new leaves may be attached to the same node.
Output
Print lines. On the -th line, print the minimum cost to clean the tree in the -th variation. If the tree cannot be cleaned, print .
Constraints
for all
for
for all in every variation
Hint
The picture shows the second variation.

One possible solution is to clean the paths between leaves 1 and 6, A and 7, and B and 3.