#K11116. Subtree Weights in a Tree
Subtree Weights in a Tree
Subtree Weights in a Tree
You are given a tree with n nodes, where each node has an associated value. The tree is given as an undirected connected graph. The root of the tree is assumed to be node 1. Your task is to compute the weight of the subtree for various query nodes. The weight of a subtree is defined as the sum of the values of all nodes in that subtree.
Formally, let \( T(u) \) represent the subtree rooted at node \( u \). If each node \( i \) has a value \( a_i \), then the subtree weight \( W(u) \) is given by:
[ W(u) = \sum_{v \in T(u)} a_v ]
You need to output the subtree weight for each queried node.
inputFormat
The input is given in the following format:
n a1 a2 ... an m u1 v1 u2 v2 ... (m lines in total representing edges) q x1 x2 ... xq
where:
n
is the number of nodes in the tree.- The second line contains
n
integers, representing the values associated with the nodes (1-indexed). m
is the number of edges in the tree. (Note: For a tree, m = n - 1.)- Each of the next
m
lines contains two integers \(u\) and \(v\) which represent an undirected edge connecting nodes \(u\) and \(v\). q
is the number of queries.- The last line contains
q
integers, where each integer is a node for which you need to compute the subtree weight.
outputFormat
Output the subtree weights for each queried node. The weights should be printed in the order of the queries, each separated by a space, on a single line.
## sample5
1 2 3 4 5
4
1 2
1 3
3 4
3 5
3
1 3 4
15 12 4
</p>