This page is still under construction.

Parts of this page are still being built. What you see may change.

Tree Pruning

Interview

Time limit2sMemory limit512 MB

Summary
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 NN 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 DD, 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 DD, or report that it is impossible.

Input

The first line contains two integers NN (1≤N≤3001 \le N \le 300) and DD (−N≤D≤N-N \le D \le N): the number of nodes and the required difference. The next NN blocks each describe one node. The first line of a block contains three integers: the id of the node (a distinct integer from 00 to N−1N-1), its colour (11 for white, 00 for black), and the number of children CC. The following CC lines each contain the id of one child of that node. The root of the tree is the node with id 00.

Output

Output, on a single line, the minimum number of prunes described above. If the required difference DD cannot be achieved, output −1-1.

Examples3

  1. Example 1

    Input
    6 3
    0 1 2
    1
    3
    1 1 2
    2
    5
    2 1 1
    4
    3 1 0
    4 0 0
    5 1 0
    
    Expected output
    1
    
  2. Example 2

    Input
    2 1
    0 1 1
    1
    1 0 0
    
    Expected output
    1
    
  3. Example 3

    Input
    3 2
    0 1 2
    1
    2
    1 1 0
    2 0 0
    
    Expected output
    1