Graph Theory37 sections · 1633 units
Open in Course

Implementation - Counting Paths

(Pseudocode)

cnt = array of size n, initialized to 0

For each path (u, v):
    lca_node = lca(u, v)
    cnt[u] += 1
    cnt[v] += 1
    cnt[lca_node] -= 2

function propagate(node):
    for each child c of node:
        propagate(c)
        cnt[node] += cnt[c]

propagate(root)
Output cnt[]

Time: O(mlogn+n)O(m \log n + n) with binary lifting for LCA, O(n)O(n) for DFS propagation.

The key: marking is O(1)O(1) per path, propagation is O(n)O(n) total. Much better than walking each path individually, which would be O(mn)O(m \cdot n).