Subtree Activation
Time limit2sMemory limit1024 MB
Given a rooted tree, find the fewest toggles so that every subtree is exactly the active set at some moment, starting and ending with all ornaments off.
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
For the New Year celebration, Bessie and her friends built a giant tree with many glowing ornaments. Bessie can turn the ornaments on and off with a remote control. Before the sun rises, she wants to toggle some ornaments in some order (an ornament may be toggled more than once) so that the tree starts and ends with no ornaments on. Bessie thinks the tree looks cool if the set of activated ornaments is exactly the subtree rooted at some vertex. She wants the toggle order to satisfy this: for every subtree, at some moment the set of all activated ornaments is exactly that subtree. Switching ornaments on and off takes energy, so she wants the fewest toggles possible.
Formally, there is a tree with vertices labeled to (), rooted at . Each vertex starts inactive. One operation toggles the state of a single vertex, from inactive to active or from active to inactive. The subtree rooted at vertex consists of all vertices such that lies on the path from to , inclusive. Find the minimum possible length of a sequence of operations that satisfies both conditions:
- For each of the subtrees, there is a moment when the set of active vertices is exactly the vertices of that subtree.
- Every vertex is inactive after the whole sequence.
Input
The first line contains .
The second line contains , where is the parent of vertex ().
Output
Output the minimum possible length of the sequence.
Hint
There are three subtrees, corresponding to , , and . Here is one sequence of operations of the minimum possible length:
activate 2
(activated vertices form the subtree rooted at 2)
activate 1
activate 3
(activated vertices form the subtree rooted at 1)
deactivate 1
deactivate 2
(activated vertices form the subtree rooted at 3)
deactivate 3