#K6711. Calculate Tree Node Depths

    ID: 32570 Type: Default 1000ms 256MiB

Calculate Tree Node Depths

Calculate Tree Node Depths

Given a rooted tree with (N) nodes (numbered from 1 to (N)) and (N-1) edges, where node 1 is defined as the root, your task is to determine the depth of several queried nodes. The depth of the root is 0, and for any other node, the depth is defined as the number of edges in the shortest path from node 1 to that node.

For example, consider the tree with 7 nodes and the following edges: (1,2), (1,3), (2,4), (2,5), (3,6), (3,7). If the queried nodes are 4, 5, and 6, then each of these nodes has a depth of 2.

inputFormat

The input is given via standard input and has the following format:

  • The first line contains an integer (N), the number of nodes in the tree.
  • The next (N-1) lines each contain two space-separated integers (u) and (v), representing an undirected edge between nodes (u) and (v).
  • The following line contains an integer (Q), the number of queries.
  • The last line contains (Q) space-separated integers, each representing a node for which the depth from the root (node 1) is to be calculated.

outputFormat

Output a single line to standard output containing (Q) space-separated integers. Each integer represents the depth of the corresponding queried node in the tree.## sample

7
1 2
1 3
2 4
2 5
3 6
3 7
3
4 5 6
2 2 2

</p>