First, we need to create a new graph GG removing all the bridge(s)/cut-edge(s). Now, we need to construct a tree TT from the new graph. For each connected component in the graph GG, create a node for the tree TT. And for each node from the original graph, keep track of which node from the original graph, belongs to which node of the tree TT.
We can complete the above operations in O(nlog(n))O(n log(n)) time complexity.
For two nodes of each bridge of the original graph, find which node of the tree TT belongs to and connect those nodes. The new graph TT we've created in this way will be always a tree. Now, create a sparse table using this tree TT.
For each query, find the distance between AA and BB using their LCA. The distance is the answer.
We can create the sparse table within O(nlog(n))O(n log (n)) time complexity and answer queries in O(log(n))O(log(n)) time complexity.

Statistics

67% Solution Ratio
rkb_rdEarliest, Jan '23
Kuddus.6068Fastest, 0.4s
mahabub.tweetLightest, 61 MB
rkb_rdShortest, 3224B
Toph uses cookies. By continuing you agree to our Cookie Policy.