#K46887. Message Time in Hierarchical Company
Message Time in Hierarchical Company
Message Time in Hierarchical Company
You are given a tree representing the hierarchical structure of a company. The tree has n employees numbered from 1 to n, and n-1 edges representing direct reporting relationships between employees. Employee 1 is the root of the hierarchy.
For each query, you must determine the minimum number of steps required for a message to travel from the sender to the receiver. In other words, for each pair of employees (u, v), compute the distance between them in the tree. The distance is defined as the number of edges in the unique path connecting u and v.
This can be formalized as follows: given two nodes u and v in a tree, let LCA(u, v) be their lowest common ancestor. Their distance is computed as:
\( d(u,v) = depth(u) + depth(v) - 2 \times depth(LCA(u, v)) \)
Your task is to implement a solution that, for each query, outputs the minimum steps required, reading from standard input and writing to standard output.
inputFormat
The input is read from stdin and has the following format:
- The first line contains an integer n representing the number of employees.
- The next n-1 lines each contain two integers u and v denoting an edge between employees u and v.
- The following line contains an integer q representing the number of queries.
- The next q lines each contain two integers u and v representing a query: the sender and the receiver respectively.
outputFormat
For each query, output a single integer on a new line representing the minimum number of steps needed for the message to travel from the sender to the receiver.
## sample7
1 2
1 3
2 4
2 5
3 6
3 7
3
4 5
6 7
4 7
2
2
4
</p>