#K45077. Balanced Tree Node Query
Balanced Tree Node Query
Balanced Tree Node Query
You are given a tree with n nodes. Each node has an associated integer value. The tree is provided as an undirected graph with n-1 edges. The tree is rooted at node 1, and for each node, its children are assigned as follows: when performing a DFS from the root, the first encountered child becomes the left child and the second becomes the right child. (Any extra children beyond two are ignored.)
A node is considered balanced if the sum of values in its left subtree equals the sum of values in its right subtree. Formally, if for a node u we let S_L(u) be the sum of values in the left subtree and S_R(u) be the sum in the right subtree, then u is balanced if:
$$ S_L(u) = S_R(u) $$
You will be given several queries. Each query is a node index, and for each query, you must determine whether the queried node is balanced.
inputFormat
The input is given in stdin and has the following format:
n v1 v2 ... vn u1 v1 u2 v2 ... (n-1 lines of edges) q q1 q2 ... qq
Here:
n
is the number of nodes.- The next line contains
n
integers representing the values of the nodes 1 through n. - Each of the next
n-1
lines contains two integers representing an undirected edge between two nodes. q
is the number of queries.- The last line contains
q
integers, each an index of a node to be queried.
outputFormat
For each query, print a line containing either YES
if the queried node is balanced, or NO
if it is not.
The output should be written to stdout.
## sample5
1 2 3 4 5
1 2
1 3
3 4
3 5
2
3 2
NO
YES
</p>