In Bob's backyard, there is a special apple tree with nodes, numbered from
to
. Node
is the root of the tree and has a depth of
. For every other node
(where
), its parent node is given, and its depth is defined as the depth of its parent plus
.
Each node contains some apples. Specifically, node has
apples, and each apple at that node provides
happiness when picked. If Bob picks
apples from node
, he gains
happiness.
However, Bob follows a few special rules when picking apples:
- If he picks any apples from node
, he must also pick at least one apple from its parent.
- This constraint applies recursively up to the root.
To protect the tree, Bob enforces a global constraint. Let be the total number of apples picked, and let
be the maximum depth among the nodes where Bob picks at least one apple. Then, Bob must satisfy the condition:
, where
is a given integer.
Given the structure of the apple tree and the apples in it, Bob wants to maximize the total happiness he can get while satisfying this constraint.
Input Specification
The first line of input contains an integer (
), the number of test cases.
In each test case, the first line contains two integers, and
(
,
,
), the number of nodes and the allowed threshold.
Each of the following lines contains three integers,
,
and
(
,
,
), the parent node of
, the number of apples at node
, and the happiness value of the apple at node
. For the root node
,
.
Output Specification
For each test case, print a single integer: the maximum total happiness Bob can gain while satisfying the constraint.
Constraints
Points | Additional constraints |
---|---|
The tree's depth is | |
No additional constraints |
Sample Input
2
5 1
0 1 1
1 1 1
1 1 3
2 1 10
3 1 4
9 15
0 1 1
1 7 2
2 5 10
1 3 1
4 3 17
4 3 18
4 4 19
1 1 1
8 1 100
Sample Output
15
316
Expalanation for Sample
Test case 1:
- Bob picks one apple from nodes 1, 2, 3, and 4.
- Total happiness = 1 + 1 + 3 + 10 = 15
- Total apples
T = 4
, maximum depthH = 3
, soT - H = 1 ≤ K = 1
✅
Comments