Under construction

Still being built. Things may change

Building a Quiet Dormitory

Time limit4sMemory limit768 MB

Summary
Given a rooted tree of one-way buildings with student counts, merge edges with the Union spell to minimize the number of reachable pairs of students in different buildings.
Level

Medium7 of 10

Topics
Tree, Dynamic programming
Solved
No attempts yet

Problem

Kakao Magic School is known for its unusual building layout, and its most unusual feature is the student dormitory. The dormitory has NN buildings, and N−1N-1 roads connect them. Every road is one-way. The dormitory has an entrance and an exit, and building 1 is the entrance. Every building except building 1 has exactly one road leading into it, and every building can be reached from building 1 by following one-way roads. Every building also has a path to the exit. However, the dormitory rules are strict, and the exit is closed at night.

Ryan teaches coding magic at Kakao Magic School. His biggest worry these days is that noise from the student dormitory next to the professor apartments keeps him awake. The dormitory is loud because many students gather in one building. Ryan wants to stop students from gathering by using the 'Union' spell to make buildings that could reach each other no longer able to do so.

The 'Union' spell joins two roads into one when the end of one road is the start of the other. That is, if one road goes from building xx to building yy and another goes from building yy to building zz, the spell removes both roads and creates one road from xx to zz. The new road does not pass through building yy.

Ryan's goal is to minimize the noise level of the dormitory. The noise level is the number of pairs (a,b)(a, b) for which student aa and student bb live in different buildings and there is a path from the building of student aa to the building of student bb. Since the exit is closed at night, nobody can leave through the exit and come back in through the entrance.

Ryan can use the 'Union' spell an unlimited number of times. Find the smallest possible noise level to help Ryan.

Input

The first line contains the number of buildings NN (2≤N≤200,0002 \le N \le 200,000).

The next line contains N−1N-1 numbers separated by spaces. The ii-th number is the number of the building where the one-way road to building i+1i+1 starts.

The next line contains NN numbers separated by spaces, giving the number of students living in each building. The number of students in one building is at least 1 and at most 10610^6.

Output

Print the smallest possible noise level on the first line.

Examples1

  1. Example 1

    Input
    4
    1 1 2
    2 1 3 2
    
    Expected output
    10