#Lutece1205. Breadth-First Search by Foxpower
Breadth-First Search by Foxpower
Migrated from Lutece 1205 Breadth-First Search by Foxpower
All parts of this problem, including description, images, samples, data and checker, might be broken. If you find bugs in this problem, please contact the admins.
Description
Fox Ciel went to JAG Kingdom by bicycle, but she forgot a place where she parked her bicycle. So she needs to search it from a bicycle-parking area before returning home.
The parking area is formed as a unweighted rooted tree with vertices, numbered 1 through . Each vertex has a space for parking one or more bicycles. Ciel thought that she parked her bicycle near the vertex 1, so she decided to search it from there by the breadth-first search. That is, she searches it at the vertices in the increasing order of their distances from the vertex 1. If multiple vertices have the same distance, she gives priority to the vertices in the order of searching at their parents. If multiple vertices have the same parent, she searches at the vertex with minimum number at first.
Unlike a computer, she can't go to a next vertex by random access. Thus, if she goes to the vertex j after the vertex i, she needs to walk the distance between the vertices i and j. BFS by fox power perhaps takes a long time, so she asks you to calculate the total moving distance in the worst case starting from the vertex 1.
Input
The input is formatted as follows.
n
p2 p3 p4 ⋯ pn
The first line contains an integer , which is the number of vertices on the unweighted rooted tree T. The second line contains n−1 integers , which are the parent of the vertex i. The vertex 1 is a root node, so does not exist.
Output
Print the total moving distance in the worst case in one line.
Samples
4
1 1 2
6
4
1 1 3
4
11
1 1 3 3 2 4 1 3 2 9
25
Resources
Japan Alumni Group Spring Contest 2014