Graph Theory37 sections · 1633 units
Open in Course

Lessons - Amortized Preprocessing

(Pay once, query many)

This problem shows the power of amortized preprocessing. Spending O(nlogn)O(n \log n) time upfront lets you answer qq queries in O(qlogn)O(q \log n) total time. If you tried to answer each query by traversing the tree, you would spend O(n)O(n) per query, making the total O(qn)O(qn).

For q=105q = 10^5 and n=105n = 10^5, that is 101010^{10} operations, which times out. Preprocessing is the difference between passing and failing on large inputs.