Binary Lifting (Gold) Part 3
What's Covered
What is node to node distance and why is it important
How to use LCA from binary lifting to calculate node to node distance
Prerequisites
Required
All prerequisites carry over from "Binary Lifting (Gold) Part 1" and "Binary Lifting (Gold) Part 2"
A thorough understanding of binary lifting from "Binary Lifting (Gold) Part 1" and a thorough understanding of LCA computation from "Binary Lifting (Gold) Part 2"
Disclaimer
This post, although considerably self-contained and full of information with great emphasis on obscure ideas, should be read and understood with care and ample time. Follow along with each piece of code as it is presented; I recommend you to have your own code file as well. This ensures that the code will be built up in digestible chunks instead of overwhelming and difficult ones.
Now that the first two parts have covered binary lifting and LCA computation, we have everything we need to efficiently query the distance between two nodes on a tree. This is simply defined as the length of the unique path from one node to the other (the number of edges on that path) in the tree.
It is straightforward to note that the path from one node to another must include the LCA of the two nodes. In particular, the strategy we can use is first jumping to the LCA and then jumping down from the LCA. This means there are two parts to our calculation, upd
and downd
, and the answer is the sum of them. To actually calculate upd
and downd
, note that we are only traveling a distance up or down the tree based on the difference in depths between the LCA and a node.
As such, we can write the following, where the whole array of depths has already been filled through the initial DFS:
More frequently, you will see this condensed as follows, removing the intermediate variables:
Then, to make a working program and answer q
queries like we have done before, we can write the following code:
And we have solved the problem.
Part 4, if made, will address more advanced problems based on the concepts from the first three parts.
Last updated