Editorial for Pursuit of Knowledge

Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

If you tried to run a BFS for each query, it is likely your code would've failed(unless it was in c++ or PYPY2 with good optimization). This is because the time cost is Q(N+M), where Q is a ridiculously huge number. Notice that there are many more queries than possible source nodes. Therefore, all we need to do is run BFS from each possible source node and store the values in an answer array. For each query, just grab the value from the answer array. In total, this solution takes N(N+M) time, a significant upgrade from the first.

Skills needed: BFS

Time complexity: O(N(N+M)+Q)

Note: The difficulty curve from J4 and J5 is quite steep. This question requires an algorithm known as Breadth First Search, which you can search up online.


  • 2
    pblpbl  commented on Oct. 6, 2019, 6:39 p.m.

    You can still pass with BFSing each query if you stop searching as soon as you find the end node

  • -4
    4n0u4r  commented on June 18, 2018, 4:24 p.m.

    Floyd Warshall algorithm would also work just fine.

  • -23
    hezeyu2007001  commented on July 26, 2017, 10:37 a.m.

    This comment is hidden due to too much negative feedback. Click here to view it.