Order the reading of a citation tree rooted at book 1 so that the sum of all book return times is minimized.
Hard8TreeGreedyDFSSortingInterviewNo attempts yetTime limit1sMemory limit1024 MBGrace 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 N books in total, numbered from 1 to N. Reading book i itself and returning it takes Ki minutes. Book i contains a citation list of Fi books. The book she originally wanted to read is book 1. Every book except book 1 appears in exactly one citation list, and there is no cycle of citations. Hence the citations form a tree rooted at book 1.
Reading one book proceeds as follows.
All books are already borrowed at time 0. The borrow time of book i is the moment it is returned. Choose the reading order so that the sum of borrow times over all books is minimized.
The first line contains the integer N (1≤N≤100000). The next N lines describe books i=1 through N in order. Each line contains Ki (1≤Ki≤1000), Fi (0≤Fi<N), followed by Fi book numbers cited by book i. Every book number except 1 appears exactly once across all citation lists.
Print a single positive integer, the minimum possible total borrow time over all books.
Since every book is borrowed at time 0, the answer equals the sum of the moments at which the books are closed. For a book u with children v, the total time of its subtree does not depend on the order and equals T(u)=1+Ku+∑T(v), so the whole process always takes N+∑Ki. 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.