Graph Theory37 sections · 1633 units
Open in Course

Core idea - Count Range Instead of Exact

(Modify the counting step)

In Fixed-Length Paths I, you counted pairs with d1+d2=kd_1 + d_2 = k.

Now you count pairs with k1d1+d2k2k_1 \le d_1 + d_2 \le k_2. The structure is identical, only the counting changes. For each distance d1d_1, you want distances d2d_2 where k1d1d2k2d1k_1 - d_1 \le d_2 \le k_2 - d_1. Use a frequency map or sorted list to count matches in that range. The rest of the algorithm is identical: find centroid, count through it, subtract same-subtree paths, recurse. Only the pair-counting logic changes.