All problems

Problem 947

Time Needed to Inform All Employees

Medium · 20 pts · Tree, Depth-First Search, Breadth-First Search

Problem

A company has N employees numbered 0 to N - 1, with a head employee HEAD. MANAGER[i] is the direct manager of employee i (-1 for the head), forming a tree. The head wants to share urgent news: each employee, once informed, needs INFORMTIME[i] minutes to inform all their direct reports at once. Find the number of minutes until everyone knows. It is the largest sum of INFORMTIME along any path from the head down to an employee.

Input

The first line contains N and HEAD. The second line contains MANAGER[0..N-1]. The third line contains INFORMTIME[0..N-1].

Output

Print the total time needed to inform everyone.

Constraints

1 <= N <= 100000; MANAGER forms a tree rooted at HEAD; 0 <= INFORMTIME[i] <= 1000; INFORMTIME[i] = 0 if employee i has no reports

Example input

6 2
2 2 -1 2 2 2
0 0 1 0 0 0

Example output

1

Explanation

With 6 employees and head 2 managing everyone else, the head needs 1 minute to tell all five, so the answer is 1.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Find Closest Node to Given Two Nodes Next: Minimum Number of Days to Disconnect Island