Monster Hunter
Time limit1sMemory limit512 MB
On a rooted tree, killing a vertex costs its hp plus the hp of its living children; with up to m free kills by spell, find the minimum total power for every m from 0 to n.
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Greedy, DFS
- Solved
- No attempts yet
Problem
There is a rooted tree with vertices, and the root vertex is . Each vertex holds a monster. The hit points of the monster in vertex are .
Kotori wants to kill all the monsters. The monster in vertex can be killed only if the monster in the direct parent of vertex has already been killed. The power needed to kill the -th monster is the sum of and the hit points of all other living monsters that live in a vertex whose direct parent is . Formally, the power equals
Kotori can also use magic spells. If she uses one magic spell, she can kill any monster using power without any restriction. That is, she can choose a monster even if the monster in its direct parent is alive.
For each , find the minimum total power needed to kill all the monsters if she can use magic spells.
Input
The input consists of multiple test cases. The first line of input contains an integer , the number of test cases. Each test case is as follows.
The first line contains an integer (), the number of vertices.
The second line contains integers (), where is the direct parent of vertex .
The third line contains integers (), the hit points of each monster.
The sum of over all test cases does not exceed .
Output
For each test case, output one line containing integers separated by spaces, where is the minimum total power needed to kill all the monsters if Kotori can use magic spells.