Graph Theory37 sections · 1633 units
Open in Course

Rerooting vs Brute Force (Why rerooting wins)

($n$ times faster)

Brute force runs BFS from every node. Each BFS takes O(n)O(n), so the total is O(n2)O(n^2). For n=200,000n = 200{,}000, that is 4×10104 \times 10^{10} operations. At 10810^8 operations per second, it takes 400400 seconds. Way too slow.

Rerooting does 22 DFS passes, each O(n)O(n). Total: O(n)O(n). For n=200,000n = 200{,}000, that is about 4×1054 \times 10^5 operations. It finishes in under a millisecond.

The speedup comes from reusing work. Each edge transition costs O(1)O(1) instead of O(n)O(n). You trade nn full DFS traversals for nn constant-time updates. That is an nn-fold improvement.