Under construction

Still being built. Things may change

Calculating Scores

Interview

Time limit2sMemory limit1024 MB

Summary
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 scorescore that the employee earns. The other is the bonusbonus score that the ancestors of the node representing an employee receive when that employee earns a scorescore. If an employee earns xx of scorescore, every ancestor node of that employee's node receives xx of bonusbonus.

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 bonusbonus, and recalculate each employee's score in the new tree using the existing scorescore 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 scorescore.

As shown in the figure, when node 1 is the root, the score of node 3 is 65: its own scorescore of 47, plus the bonusbonus of 18 from node 4, which earns a scorescore 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 scorescore of 16, plus the bonusbonus values of 43, 47, and 18 that node 2 receives when nodes 1, 3, and 4 earn their scorescore values.

To handle such cases, the program must process the following query QQ times.

  • rr vv: the score of employee vv when node rr 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 NN and the number of queries QQ, separated by a space. (1≤N≤100 0001 \le N \le 100\,000; 1≤Q≤100 0001 \le Q \le 100\,000)

The second line contains the scorescore of each employee from 1 to NN, in order, separated by spaces. (0≤score≤10 0000 \le score \le 10\,000)

The next N−1N - 1 lines each contain uu and vv, separated by a space, describing an edge of the tree. (1≤u,v≤N1 \le u, v \le N)

The next QQ 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.

Examples1

  1. Example 1

    Input
    5 10
    43 16 47 18 63
    1 2
    1 3
    3 4
    2 5
    1 1
    5 2
    2 3
    3 4
    1 5
    3 5
    2 3
    1 3
    2 4
    4 1
    
    Expected output
    187
    124
    65
    18
    63
    63
    65
    65
    18
    122