Experience
Time limit2sMemory limit512 MB
Given a rooted tree with values on nodes, partition nodes into vertex-disjoint downward paths to maximize the sum over paths of (max value minus min value).
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Greedy, DFS
- Solved
- No attempts yet
Problem
Company X has employees. The company has a strict hierarchical tree structure. The CEO (chief executive officer) is at the top (the root of the tree) and has some number of direct subordinates, who have direct subordinates of their own, and so on down to the regular employees, who have no subordinates (the leaves of the tree).
The employees are numbered from 1 to . The CEO has number 1, and the other numbers have nothing to do with the hierarchy. Each employee has some experience: employee has experience , a non-negative integer.
The company has a large number of group projects to complete, so the management splits all of the employees into teams. The split must satisfy both conditions below.
- Each team consists of at least one person, and each person belongs to exactly one team.
- Each team consists only of people who are consecutive subordinates of one another. A group of employees is a valid team when is a direct subordinate of , is a direct subordinate of , is a direct subordinate of , and so on.
After a group project is finished, the total experience of the team assigned to that project increases by , where is the largest experience and is the smallest experience among the members of the team. The total experience increase for the company is the sum of the increases of all teams. The management wants to maximize the total increase for the company by choosing the best possible split under the two conditions above.
Write a program that computes the maximum possible experience increase for the company.
Input
The first line contains a single integer , the number of employees in the company.
The second line contains space separated non-negative integers , the experience of each employee.
Each of the next lines contains two space separated integers and in that order. Employee is a direct subordinate of employee .
Output
Print one integer, the maximum total experience increase for the company.
Constraints
Note

The picture shows a company of 7 employees. The number inside a circle is the employee number, and the red number next to it is that employee's experience. One split that reaches the maximum total increase is {1, 5, 3}, {6, 2, 4}, {7}. The split {1, 5}, {3}, {6, 2, 4}, {7} reaches the same maximum.