Solution This task can be solved by dynamic programming. Let us root the tree by choosing one of the leaves as a root. Then we can process the tree in a bottom-up order. For each vertex we should compute two solutions for a sub-tree rooted in the given vertex: - the optimal solution, together with the gems g used for the given vertex; - the optimal solution, assuming, that the given vertex is modelled by a gem different from g.