The Leisurely Stroll
Time limit1sMemory limit128 MB
Given a rooted tree of choice-nodes where leaf edges lead to pastures, find the maximum number of edges on any root-to-pasture path.
- Level
Easy3 of 10
- Topics
- Tree, DFS, Recursion, Implementation
- Solved
- No attempts yet
Problem
Bessie steps out of the barn on a beautiful spring day and wants to enjoy the longest possible walk to the pastures before breakfast. Starting at the barn (node ), she walks along a path until she reaches a choice-node, where she picks one of two paths. She keeps choosing at each choice-node until a path finally leads her to a pasture.
Bessie wants to make the set of choices that lets her walk over the greatest number of cow paths on the way to a pasture. Given the layout of the paths, determine how many cow paths she traverses when she walks to the furthest pasture.
The farm has () pastures, reached through choice-nodes numbered and connected by paths. From the barn (node ) there is exactly one route to any choice-node or pasture, so the paths form a tree rooted at the barn.
The picture below shows the paths (lines), the pastures (%), and, on the right, one highlighted (#) route to a pasture:
% %
/ /
2----% 7----8----% 2----% 7####8----%
/ \ / \ # # # #
1 5----6 9----% 1 5####6 9----%
\ \ \ \ \ \ \ #
\ % % % \ % % %
\ \
3-----% 3-----%
\ \
4----% 4----%
\ \
% %
The pasture reached through choice-node is one of two pastures that let Bessie walk over seven different cow paths on the way to breakfast; these are the furthest pastures from the barn (node ).
Each choice-node is described by three integers , , and . is the node number (); and are the two destinations reachable from that node (, ). A destination of means that direction leads to a pasture; any other value is the number of the choice-node reached in that direction.
Input
- Line : a single integer .
- Lines : line contains three space-separated integers describing one choice-node: , , and .
Output
- Line : a single integer, the largest number of cow paths Bessie can traverse on the way to the furthest pasture.
Hint
The route 1-2-5-6-7-8-9-P (ending at a pasture) is one of the longest possible walks.