Graph Theory37 sections · 1633 units
Open in Course

Walkthrough - Example

(Tracing the algorithm)

Consider a tree: root 11 with children 2,32, 3. Node 22 has child 44. Paths: (4,3)(4, 3) and (2,3)(2, 3).

The correct formula marks 44 positions per path: cnt[u] += 11, cnt[v] += 11, cnt[lca(u, v)] -= 11, cnt[parent[lca(u, v)]] -= 11. The parent decrement stops the path contribution from leaking above the LCA.

Path (4,3)(4, 3): lca=1lca = 1. Mark cnt[44] += 11, cnt[33] += 11, cnt[11] -= 11, cnt[parent[11]] -= 11.

Path (2,3)(2, 3): lca=1lca = 1. Mark cnt[22] += 11, cnt[33] += 11, cnt[11] -= 11, cnt[parent[11]] -= 11.

After DFS propagation, each node's count reflects how many paths pass through it. Test your code to make sure the LCA adjustment is correct.