Counterspells
Time limit1sMemory limit1024 MB
After each of n leaf insertions into a rooted tree, find the minimum number of vertex recolorings needed to restore the unique well coloring.
- Level
Hard8 of 10
- Topics
- Tree, DFS, Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
The card game Magic: The Gathering has a rule for casting and countering spells. The coloring rule below comes from it. The card game itself is not explained here, and you do not need to know it to solve this problem.
For every rooted tree there is exactly one way to color the vertices black and white that satisfies this condition:
- A vertex is white if and only if it has a black child.
Induction proves that this coloring is unique. A tree colored this way is called well colored.
Start with a tree that consists of one black vertex, the root, and perform the following operation times:
- : attach a new black vertex to the tree as a child of vertex . Then invert the colors of some vertices so that the tree is well colored again. You may invert none of them, and you may invert all of them.
For each operation, find how many vertices are inverted.
Input
The root is numbered , and the other vertices are numbered in the order they are added to the tree.
The first line contains one integer , the number of vertex additions. ()
Each of the next lines contains one integer , the parent of the vertex added in the -th operation. Vertex already exists before the -th operation, so .
Output
Print lines. The -th line contains the number of vertices whose color is inverted during the -th operation. The vertex attached by that operation arrives black and a leaf is always black, so it is never one of the inverted vertices.
Note
The figure below shows the starting tree of the first example and the tree after each operation. The vertices inverted by that operation have a red outline.
