Marbles on a Tree
Time limit1sMemory limit128 MB
Given a rooted tree where each vertex has a box and the total marbles equal the number of vertices, find the minimum number of moves (along edges) so every box holds exactly one marble.
- Level
Medium6 of 10
- Topics
- Tree, DFS, Greedy, Dynamic programming
- Solved
- No attempts yet
Problem
A box sits on each vertex of a rooted tree. The vertices are numbered from to , where . Each box holds some marbles or is empty, and the total number of marbles placed across the whole tree is exactly .
A single move takes one marble out of a box and places it into the box on an adjacent vertex (its parent or one of its children). Write a program that computes the minimum number of moves needed so that every box holds exactly one marble.
Input
The input consists of several test cases. The first line of each test case contains the number of vertices . Each of the next lines describes one vertex: the vertex number , the number of marbles initially in the box at , and the number of children of , followed by the child numbers of .
A line containing marks the end of the input and must not be processed.
Output
For each test case, print on its own line the minimum number of moves required to leave exactly one marble in every box.