Calculating Scores
InterviewTime limit2sMemory limit1024 MB
Given a tree with node scores, answer each query for node v's total score when node r is the root, which is the sum of scores in v's subtree.
- Level
Medium5 of 10
- Topics
- Tree, DFS, Prefix sum
- Solved
- No attempts yet
Problem
You are building a program that manages scores of employees. The org chart of a company can be represented as a tree, where each employee is a node and the direct supervisor is the parent node. The root of this tree is the president.
The program gives each employee two kinds of scores. One is the that the employee earns. The other is the score that the ancestors of the node representing an employee receive when that employee earns a . If an employee earns of , every ancestor node of that employee's node receives of .
The company has a new requirement. When the president changes, keep all edges, build a new tree rooted at the new president, reset every employee's , and recalculate each employee's score in the new tree using the existing values.

For example, consider the situation above. In the figure, the number inside each node is the node number, and the small number beside each node is its .
As shown in the figure, when node 1 is the root, the score of node 3 is 65: its own of 47, plus the of 18 from node 4, which earns a of 18.

If the root is changed to node 5, the tree takes the shape shown above. Then the score of node 2 is 124: its own of 16, plus the values of 43, 47, and 18 that node 2 receives when nodes 1, 3, and 4 earn their values.
To handle such cases, the program must process the following query times.
- : the score of employee when node is the root
Write a program that finds the answer to each query, given the tree, the score of each employee, and the queries.
Input
The first line contains the number of nodes and the number of queries , separated by a space. (; )
The second line contains the of each employee from 1 to , in order, separated by spaces. ()
The next lines each contain and , separated by a space, describing an edge of the tree. ()
The next lines contain the queries.
The given graph is a tree.
Output
Print the answer to each query on its own line, in the order the queries were given.