Citations
InterviewTime limit1sMemory limit1024 MB
Order the reading of a citation tree rooted at book 1 so that the sum of all book return times is minimized.
Problem
Grace wants to read one science book. To understand it fully, she reads every book it cites, then every book those books cite, and so on. There are books in total, numbered from to . Reading book itself and returning it takes minutes. Book contains a citation list of books. The book she originally wanted to read is book . Every book except book appears in exactly one citation list, and there is no cycle of citations. Hence the citations form a tree rooted at book .
Reading one book proceeds as follows.
- Open the book and read its citation list, which takes minute.
- Read all books in the list, in any order she chooses.
- Read the main text and return the book, which takes minutes.
All books are already borrowed at time . The borrow time of book is the moment it is returned. Choose the reading order so that the sum of borrow times over all books is minimized.
Input
The first line contains the integer (). The next lines describe books through in order. Each line contains (), (), followed by book numbers cited by book . Every book number except appears exactly once across all citation lists.
Output
Print a single positive integer, the minimum possible total borrow time over all books.
Hint
Since every book is borrowed at time , the answer equals the sum of the moments at which the books are closed. For a book with children , the total time of its subtree does not depend on the order and equals , so the whole process always takes . The problem therefore reduces to choosing the order of children at each node, and the total is the sum inside the child subtrees plus the waiting time between siblings.