#P6293. [eJOI 2017] 经验
[eJOI 2017] 经验
Description
Company X has employees. The relationships among the employees form a tree structure. The CEO is at the top of the structure (the root of the tree). The CEO has some subordinates (the children of the root), and those subordinates have their own subordinates, and so on. Finally, there are some bottom-level employees (the leaves) who have no subordinates.
The employees are numbered from to , and the CEO is employee . Each employee has an experience value. The experience value of employee is .
The company has a large project to complete, so the managers want to split and reorganize this tree structure into smaller teams. The splitting must follow these rules:
- Each team contains at least one person, and each employee must belong to exactly one team.
- For any team, suppose its members, sorted from lower rank to higher rank in the original hierarchy, are . Then it must hold that: for all , is the manager of .
Define the total experience value of a team as the range of experience values among all members of that team; in other words, the maximum experience value in the team minus the minimum experience value in the team. The total experience value of the whole company is the sum of the experience values of all teams.
Your task is to find the maximum total experience value the company can obtain.
Input Format
The first line contains an integer .
The second line contains integers: .
The next lines each contain two integers , indicating that is a subordinate of .
Output Format
Output one integer representing the answer.
7
5 5 3 6 2 3 3
1 6
5 3
1 5
6 2
2 4
6 7
6
Hint
Explanation of Sample 1

One possible grouping is .
Another possible grouping is .
Constraints
- For about of the testdata, it is guaranteed that .
- For about of the testdata, it is guaranteed that .
- For another about of the testdata, it is guaranteed that each employee has at most one subordinate.
- For all testdata, it is guaranteed that and .
Notes
The original problem is from: eJOI2017 Problem E Experience.
Translation provided by: @_Wallace_.
Translated by ChatGPT 5
京公网安备 11011102002149号