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).
Hard8TreeDynamic programmingGreedyDFSNo attempts yetTime limit2sMemory limit512 MBCompany X has N 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 N. The CEO has number 1, and the other numbers have nothing to do with the hierarchy. Each employee has some experience: employee i has experience Wi, 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.
After a group project is finished, the total experience of the team assigned to that project increases by Wmax−Wmin, where Wmax is the largest experience and Wmin 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.
The first line contains a single integer N, the number of employees in the company.
The second line contains N space separated non-negative integers W1,W2,…,WN, the experience of each employee.
Each of the next N−1 lines contains two space separated integers u and v in that order. Employee v is a direct subordinate of employee u.
Print one integer, the maximum total experience increase for the company.

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.