| Codeforces Round 1114 (Div. 3) |
|---|
| Finished |
Yousef has given you a rooted tree$$$^{\text{∗}}$$$ with $$$n$$$ vertices, where the root is vertex $$$1$$$. Each vertex $$$i$$$ is assigned an integer $$$a_i$$$.
You must partition the set of all $$$n$$$ vertices into exactly $$$k$$$ disjoint subsets $$$S_1, S_2, \dots, S_k$$$ (that is, each vertex must belong to exactly one of the $$$k$$$ sets) such that the following condition is satisfied:
The score of a subset $$$S_i$$$ is defined as the maximum value $$$a_u$$$ among all vertices $$$u$$$ in that subset. The score of the partition is the sum of the scores of the $$$k$$$ subsets. In other words, the score of the partition is equal to $$$\sum\limits_{i=1}^{k} \max\limits_{u \in S_i} a_u$$$.
For every integer $$$k$$$ from $$$1$$$ to $$$n$$$, calculate the maximum possible score of a partition. If it is impossible to partition the tree into exactly $$$k$$$ subsets that satisfy the condition, output $$$-1$$$.
$$$^{\text{∗}}$$$A tree is a connected graph without cycles. A rooted tree is a tree where one vertex is special and called the root.
$$$^{\text{†}}$$$An ancestor of vertex $$$v$$$ is any vertex on the simple path from $$$v$$$ to the root, including the root, but not including $$$v$$$. The root has no ancestors.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.
The first line of each test case contains an integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices.
The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the values of the vertices.
The third line of each test case contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i \lt i$$$), where $$$p_i$$$ is the parent of the $$$i$$$-th vertex.
It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
For each test case, output a single line containing $$$n$$$ space-separated integers. The $$$k$$$-th integer should represent the maximum possible score for a partition of $$$k$$$ subsets. If it is impossible to partition the tree into $$$k$$$ subsets, output $$$-1$$$ for that value.
7310 20 301 145 10 15 201 2 241 2 3 41 1 351 2 3 4 51 2 3 491 100 1 90 80 1 2 3 41 1 2 4 3 3 3 365 4 10 3 9 11 2 1 4 1410 10 20 11 2 1
-1 50 60-1 35 45 50-1 6 9 105 9 12 14 15-1 -1 -1 -1 110 200 280 281 282-1 -1 24 28 31 32-1 30 40 41
In the first test case:
The given tree in the first test case. In the second test case:
The given tree in the second test case.
| Name |
|---|


