#C3472. Subtree Sums
Subtree Sums
Subtree Sums
You are given a tree with n nodes. Each node has an associated integer value. Your task is to answer q queries. For each query, given a node u, compute the sum of the values of all nodes in the subtree rooted at node u. In other words, if we denote by \(T(u)\) the set of nodes in the subtree of u, you need to compute
\(\sum_{v \in T(u)} a_v\)
where \(a_v\) is the value of node v. The tree is provided as an undirected graph where node 1 is considered the root for the purpose of computing subtree sums.
inputFormat
The input is read from standard input (stdin) and has the following format:
- An integer
n
representing the number of nodes. n
space-separated integers representing the values of the nodes (from node 1 to node n).- An integer
m
representing the number of edges. (Note: For a tree,m = n - 1
.) m
lines follow, each with two space-separated integersu
andv
representing an edge between nodesu
andv
.- An integer
q
representing the number of queries. - A line with
q
space-separated integers, each denoting a query node.
outputFormat
For each query, output a single line containing the sum of the values in the subtree rooted at the given node.
The output is written to standard output (stdout), with each answer on a new line.
## sample5
10 20 30 40 50
4
1 2
1 3
3 4
3 5
3
1 3 4
150
120
40
</p>