Given a tree with **N** vertices numbered from **0** to **N – 1, ** **M **edges, and **Q** queries of the form **{U, V}, **such that there is a direct edge between **U **and **V** in the tree. The task for each query is to find all possible shortest paths between any possible unordered pair of vertices from the given tree which contains the edge between the given pair of nodes.

**Input: **N = 6, M[] ={{0, 1}, {0, 2}, {1, 3}, {3, 4}, {3, 5}}, queries[] = {{1, 3}, {0, 2}}** **0

/

1 2

/

3

/

4 5**Output:**

9

5**Explanation:**

Query 1: The edge (1, 3) lies in the paths {1, 3), (1, 3, 4), (1, 3, 5), (0, 3), (0, 4), (0, 5), (2, 3), (2, 4) and (2, 5).

Query 2: The edge (0, 2) lies in the paths (2, 0), (2, 1), (2, 3), (2, 4) and (2, 5).

**Input: **N = 6, M[] ={{0, 1}, {0, 2}, {2, 3}, {1, 4}, {1, 5}}, queries[] = {{1, 5}, {0, 2}}** **0

/

1 2

/ /

4 5 3**Output:**

5

8

**Approach: **The problem can be solved based on the observation that for any query **{U, V}, **the shortest path between any pair of nodes in the tree will contain the given edge **(U, V)** if one of the nodes lie in the subtree of **U** and the other node lies in the remaining tree. Therefore, the required number of pairs will be:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Leave a Reply