#C7623. Count Subtree Nodes Excluding the Root
Count Subtree Nodes Excluding the Root
Count Subtree Nodes Excluding the Root
Given a rooted tree with \(n\) vertices (with vertex 1 as the root) and \(n-1\) edges, you are asked to process \(q\) queries. For each query, given a vertex \(v\), compute the number of nodes in the subtree of \(v\) excluding \(v\) itself.
A subtree of a vertex \(v\) is defined as \(v\) and all vertices that are descendants of \(v\). Thus, the answer for a query vertex \(v\) is \(\text{subtree_size}(v) - 1\), where \(\text{subtree_size}(v)\) is the total number of nodes in the subtree rooted at \(v\).
Note: The input guarantees that the given graph is a tree. Use depth-first search (DFS) to efficiently calculate subtree sizes.
inputFormat
The input is read from standard input (stdin) and has the following format:
- The first line contains a single integer \(n\) (\(2 \le n \le 10^5\)), the number of vertices in the tree.
- The next \(n-1\) lines each contain two space-separated integers \(u\) and \(v\), representing an edge between vertices \(u\) and \(v\).
- The following line contains a single integer \(q\) (\(1 \le q \le 10^5\)), the number of queries.
- The next line contains \(q\) space-separated integers, each denoting a query vertex.
outputFormat
Output a single line to standard output (stdout) containing \(q\) integers separated by a space. The \(i\)-th integer is the answer to the \(i\)-th query — the number of nodes in the subtree of the queried vertex excluding the vertex itself.
## sample7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 3 4
2 2 0
</p>