Chapaev on a Tree
Time limit2sMemory limit1024 MB
For each vertex as Root, count the games on its descendants where Marina moves first and flicks checkers toward the root, then report how many she wins.
- Level
Hard8 of 10
- Topics
- Tree, Game theory, DFS, Dynamic programming
- Solved
- No attempts yet
Statement
Vova and Marina like games, and they especially like inventing their own rules for them. Recently they discovered the fun game "Chapaev", where players flick checkers of the opposing color off a chessboard (this game is also known as "Nutcrackers"). After playing it enough, they decided to add mathematical complexity to the rules.
Now they do not play on a chessboard. They play on a board shaped like a tree! Their tree has vertices. Vertex 1 is the root, and every other vertex has an edge to a parent vertex with a smaller number.
Checkers of one color are used in the game. At the start, they are placed on some vertices of the tree. On a turn, a player picks one checker and flicks it toward the root along the edges of the tree. Every checker it meets on the way is knocked off the board. The flicked checker itself also falls off the board once it reaches the root.
The players take turns. The player whose turn comes when no checkers remain on the board loses.
The same board can be used for games that start from different initial positions. In practice, the most interesting games come from placing a checker on every vertex that is a descendant (direct or indirect) of some vertex . No checker is placed on itself.
The children decided to play games, choosing each vertex as exactly once. If the current has no descendants and the board starts with no checkers, no game takes place, and the children move on to the next setup. Marina moves first in every game.
Vova asks you in how many games Marina can win if both players play optimally.
Input
The first line contains an integer (), the number of vertices in the tree.
The second line contains integers separated by spaces, where is the number of the parent of vertex ().
Output
Print a single integer: the number of games that Marina wins.
Hint
Consider the test from the statement. The board is shown in the pictures below. The children play four games, choosing vertices 1, 2, 3, and 5 as . If you choose any of the other three vertices as , the board starts with no checkers, so no game takes place.
If you choose vertex 5 as , the checkers start on vertices 6 and 7. Marina loses this game. After she knocks off either of these two checkers, Vova knocks off the remaining one and ends the game.
If you choose vertex 2 or 3 as , Marina can win in one move by flicking the checker on vertex 4. When , that flick also knocks off the checker on vertex 3 along the way.

Marina also has a winning strategy if you choose vertex 1 as . Her first move must knock off the checker on vertex 2. The picture below shows a game from this starting position.

So Marina wins three games.