Parents
Time limit5sMemory limit128 MB
Pick from 1 to K nodes of a valued tree with no parent-child pair so the sum of picked values is as large as possible.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Tree
- Solved
- No attempts yet
Problem
You are given a rooted tree whose nodes each carry an integer value. The value of a set of nodes is the sum of the values of the nodes it contains.
For a positive integer , a -anti-parental subset is a set of nodes that satisfies both of the following:
- it contains between and nodes, inclusive;
- no node in the set is the parent of another node in the set (equivalently, the set contains no parent-child pair).
Given a node-valued tree and , compute the maximum possible value of a -anti-parental subset.
Input
The first line contains the number of test cases . Each test case is given as follows.
The first line of a test case contains two integers and : the number of nodes and the parameter , with and . Nodes are indexed from to , and node is always the root.
The second line contains integers, the values of nodes through in order, each in the range .
The third line contains integers: the parent index of each node from to , in increasing order of index. The first of these integers is the parent of node . The root (node ) has no parent entry. When this line is empty.
Output
For each test case, print a single line containing the maximum possible value of a -anti-parental subset of that tree.