Tree Pruning
InterviewTime limit2sMemory limit512 MB
Given a rooted binary tree with colored nodes, prune subtrees to make the whites minus blacks equal exactly D, minimizing the number of prunes.
- Level
Medium6 of 10
- Topics
- Tree, Dynamic programming, DFS, Recursion
- Solved
- No attempts yet
Problem
You are given a rooted tree with nodes in which every node has at most two children. Each node is either black or white. A prune is the operation of deleting a node together with the whole subtree rooted at that node. Given an integer , find the minimum number of prunes needed to obtain a tree in which (the number of white nodes) (the number of black nodes) equals exactly , or report that it is impossible.
Input
The first line contains two integers () and (): the number of nodes and the required difference. The next blocks each describe one node. The first line of a block contains three integers: the id of the node (a distinct integer from to ), its colour ( for white, for black), and the number of children . The following lines each contain the id of one child of that node. The root of the tree is the node with id .
Output
Output, on a single line, the minimum number of prunes described above. If the required difference cannot be achieved, output .