PROBLEM LINKS
DIFFICULTY
EASY
EXPLANATION
Restating the problem in terms of Graph Theory, we're given a set of edges, and we've to identify if two given query points are connected via these edges or not. One could do a depth first search (DFS) from one of the vertices and monitor if the other vertex is visited or not, but time limits were set in such a way that it was difficult to get accepted if one is doing a dfs at each query. Instead, after only one DFS, we could store all the connected components. After that each query can be answered in constant time. Look at tester's solution.
Alternate approach could be to build union-find data structure over the graph. As before, each query could now be answered in constant time. Look at setter's solution for this approach. So in both the solutions, desired time complexity was O(E +V + Q)
SETTER'S SOLUTION
Can be found here.
TESTER'S SOLUTION**
Can be found here.