#K91887. Subtree Sum Queries

    ID: 38075 Type: Default 1000ms 256MiB

Subtree Sum Queries

Subtree Sum Queries

Given a tree with (N) nodes where each node is assigned an integer value, you are required to calculate the sum of values in the subtree of specified nodes. The tree is rooted at node 1. For a node (u), its subtree is defined as ({u} \cup {v : v \text{ is a descendant of } u}), and the subtree sum is computed by (\sum_{v \in \text{subtree}(u)} a_v), where (a_v) is the value of node (v).

Input format and output format details are provided below. Your program should read from standard input (stdin) and write to standard output (stdout).

inputFormat

Input is given in the following format from stdin:

N
a1 a2 ... aN (N integers representing the node values, given in order from node 1 to node N)
Next, there are N-1 lines, each containing two integers u v representing an undirected edge between nodes u and v.
Then, a line containing a single integer Q denoting the number of queries.
Finally, a line with Q integers where each integer is a query representing a node whose subtree sum is to be computed.

outputFormat

For each query, output the sum of values of nodes in the subtree of the queried node on a separate line.## sample

5
1 2 3 4 5
1 2
1 3
2 4
2 5
3
1 2 3
15

11 3

</p>