Cookie Game
Time limit8sMemory limit1024 MB
Given a tree where each vertex has 1 or 2 cookies, find the maximum number of cookies a piece can eat when it starts anywhere and moves along edges.
- Level
Medium6 of 10
- Topics
- Tree, Dynamic programming, DFS
- Solved
- No attempts yet
Problem
There is an undirected tree with vertices, numbered 1 through . Each vertex has either one or two cookies on it.
You play a game on this tree. First, you choose one vertex and place a piece on it. Then you repeat the following action until the game ends.
- Eat exactly one cookie on the vertex where the piece currently is. Then choose a vertex adjacent to the current one and move the piece there. If the destination has no cookies left, the game ends at that moment.
If you play optimally, what is the maximum number of cookies you can eat during the game?
Input
The input contains at most 50 datasets. Each dataset has the following format.
N
x1x2...xN
p1
p2
…
pN-1
The first line gives the number of vertices (). The second line is a string of characters, each 1 or 2. The -th character is the number of cookies initially on vertex . The next lines give the adjacency information. The integer on line () means that vertex is adjacent to vertex .
The input ends with a line containing a single zero.
Output
For each dataset, print on one line the maximum number of cookies you can eat during the game.