Iaroslav-Menelaos Trapanache, known as the Thunderbolt of the Lower Danube, or (to his close friends) the Pharaoh, wants to become wiser, and feels like solving a computer science problem about trees that are as equidistant and correct as he is, so he composed the following problem.
Equidistant tree. A rooted tree is called equidistant if all its leaves are at the same distance from the root. (Recall that the distance between two nodes is given by the number of edges of the unique elementary path between the two nodes.)
For example, the following tree rooted at node is equidistant:

, whereas the following one (also rooted at node ) is not equidistant:

, because the distances from node to nodes , , are not all equal.
Value of a tree. Consider a tree with nodes numbered , where each node has a weight (which can also be negative). The value of tree , denoted , is defined as follows. Consider any way of successively removing leaves of tree such that the tree becomes or remains equidistant as a result, while keeping the root node. (We may remove a node that becomes a leaf as a result of removing other nodes.) Let be the nodes remaining after this removal process. The value of is the maximum possible sum over all ways of removing leaves from .
For example, let's consider the second tree above (the one with nodes). Some of the sets of nodes that can remain after removals are (we remove node ), (we remove nodes , ), (we remove nodes , , , in this order), and (we remove nodes , , , , , in this order). If we assign this tree the weights , then its value is: .
Requirement
We are given a tree with nodes rooted at node , and with weights . Let be the subtree of rooted at node . Compute .
Input Data
On the first line of the input file echidistant.in is the number of nodes of tree . On the second line are the numbers in order, separated by spaces. On the third line are numbers , representing the fact that the edges of the tree are , , , .
Output Data
The single line of the output file echidistant.out contains numbers, namely separated by spaces, in this order.
Constraints and Notes
- for
- for
| # | Score | Constraints |
|---|---|---|
| 1 | 9 | for |
| 2 | 12 | |
| 3 | 21 | |
| 4 | 44 | |
| 5 | 14 | No additional restrictions |
Example
echidistant.in
6
0 -10 10 1 -1 -1
1 2 2 3 3
echidistant.out
1 1 10 1 -1 -1
Explanation
This is the second tree from the statement, the one with nodes, where we assign the weights to nodes .