Natural Paths
Adelaide University has built a lot of new paths to combine the two old universities during the merger. These paths take quite a scenic route through Adelaide, however, and students have been forming shortcuts that jump directly from an earlier intersection to a later intersection on the same route!
Jack has decided that he wants to find the optimal way to walk between the two universities, including using these shortcuts. He has simplified the route as a series of intersections, numbered from to
. Jack always starts at intersection
. When an intersection has no further paths, Jack has reached his destination.
At any intersection, there are at most two paths Jack can take. A path either leads to a new intersection further along the route, or encodes a shortcut whose other endpoint is an earlier intersection on Jack's current route. Shortcuts never connect intersections on different branches, and no two shortcuts overlap - that is, no shortcut's target lies within another shortcut's range on any given route.
When Jack takes a shortcut from intersection back to intersection
, he skips all intersections strictly between
and
on his current route. Jack knows that he will have to walk back to where he came from after his classes are finished, so he needs your help to find a path with the maximum number of intersections he can skip by taking shortcuts.
Input
The first line contains a single integer, (
), the number of intersections.
Each of the next lines contain two integers,
and
(
), representing the paths leaving the
-th intersection. If
or
is equal to
, this indicates that there is no path.
Note: If there is a shortcut, it will always be the first path. There will be at most one shortcut per intersection.
Output
Output the maximum number of intersections Jack can skip along any route.
Example
Input 1
7
1 -1
2 3
4 -1
-1 -1
5 6
-1 -1
1 -1
Output 1
2
Intersection , which is along the path
, encodes a shortcut whose target is intersection
. This allows the route to be shortened to
, skipping
intersections.
Input 2
10
1 -1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 -1
9 -1
0 -1
Output 2
8
Comments