Building a Quiet Dormitory
Time limit4sMemory limit768 MB
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 buildings, and 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 to building and another goes from building to building , the spell removes both roads and creates one road from to . The new road does not pass through building .

Ryan's goal is to minimize the noise level of the dormitory. The noise level is the number of pairs for which student and student live in different buildings and there is a path from the building of student to the building of student . 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 ().
The next line contains numbers separated by spaces. The -th number is the number of the building where the one-way road to building starts.
The next line contains 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 .
Output
Print the smallest possible noise level on the first line.