Most Profitable Team

easyGraphDFS

You are given a company with $$$n$$$ employees, numbered from $$$1$$$ to $$$n$$$. The company follows a hierarchical structure such that every employee (except the CEO) has exactly one direct boss. The CEO (employee $$$1$$$) does not report to anyone.

Each employee generates a certain profit (or loss) for the company. You are given the profit/loss value for each employee.

For any employee $$$x$$$, define their team as:

  • Employee $$$x$$$ themselves, and
  • All employees who (directly or indirectly) report to employee $$$x$$$.

The total profit of a team is the sum of profit/loss values of all employees in the team.

Your task is to determine the maximum profit among all such teams in the company.

Input Format:

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of employees in the company.

The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$), where $$$p_i$$$ denotes the direct boss of employee $$$i$$$.

The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-200 \leq a_i \leq 200$$$), where $$$a_i$$$ represents the profit/loss value of employee $$$i$$$.

Output Format:

Print a single integer — the maximum profit made by any team.

Examples:

Example 1:

Input:

5
1 1 2 3
5 -2 3 4 -1

Output:

9

Note:

Explanation of the sample test.

We are given:

  • $$$n = 5$$$
  • Boss list: $$$[1, 1, 2, 3]$$$
  • Profit/loss list: $$$[5,\ -2,\ 3,\ 4,\ -1]$$$

This represents the following company hierarchy:

  • Employee $$$1$$$ is the CEO.
  • Employees $$$2$$$ and $$$3$$$ report to employee $$$1$$$.
  • Employee $$$4$$$ reports to employee $$$2$$$.
  • Employee $$$5$$$ reports to employee $$$3$$$.

Now, we compute the total profit for each team (i.e., the subtree sum rooted at each employee):

  • Team of employee $$$1$$$: $$$5 + (-2 + 4) + (3 + (-1)) = 9$$$
  • Team of employee $$$2$$$: $$$-2 + 4 = 2$$$
  • Team of employee $$$3$$$: $$$3 + (-1) = 2$$$
  • Team of employee $$$4$$$: $$$4$$$
  • Team of employee $$$5$$$: $$$-1$$$

The maximum profit among all teams is $$$\boxed{9}$$$.

Code

Loading Editor...