Data Structures19 sections · 729 units
Open in Course

MO's Optimization - Zigzag Order

Reducing constant factor

The standard MO sorting has a hidden inefficiency. When moving to a new ll-block, rr might jump from high to low, causing O(n)O(n) movement.

Fix: alternate sorting direction of rr for odd vs even ll-blocks. pseudocode sort queries by: primary key: floor(l / B) secondary key: r if block is even, else -r This zigzag pattern makes rr sweep back and forth instead of jumping.

In practice, this can speed up MO's algorithm by 2×2\times or more. The total complexity is still O((n+q)n)O((n + q)\sqrt{n}), but the constant factor drops by roughly half. Time: O((n+q)n)O((n + q)\sqrt{n}). Space: O(n)O(n).