Orchard Optimiser
You are working on a farm that owns a magically big apple tree with strange behaviours, and you want to optimise the amount of fruit you can harvest from it. The apple tree has a complex branching layout, where each junction grows a magical fruit with a certain mass. However, if two apples that are connected by a branch are harvested at the same time, they will spoil, becoming worthless and inedible. You want to maximise the total mass of the apples you harvest without harvesting any two adjacent fruit.
Input
The first line contains a single integer , the number of apple-bearing nodes in the tree. The nodes are numbered
through
.
The next line contains space-separated integers
, the mass of each of the
apples.
The next line contains space-separated integers, the parent of each node. Since node
is the root of the tree, the first integer on this line is the parent of the
nd node.
Output
Output the total mass of apples you can obtain by only taking non-adjacent apples from the tree.
Example
Input 1
7
5 3 4 2 6 1 7
1 1 2 2 3 3
Output 1
21
The tree here forms a complete binary tree. It is optimal to take the root apple, and all the apples on the lowest level, for a total of .
Input 2
10
10 3 7 5 2 3 9 1 3 2
1 1 2 2 5 5 7 7 7
Output 2
27
Here we should takes apples for a total mass of
Comments