Official

B - Abs Abs Function Editorial by evima


Observing the graph reveals \(\left| \left|x-a\right| -b \right| = \min(\left|x-(a-b)\right|,\ \left|x-(a+b)\right|)\). Thus, if we define an integer set \(S'=\{a-b,\ a+b \mid (a,\ b) \in S\}\), we have \(f_S(x)=\min_{y \in S'} \left|x-y\right|\).

Then, for a type-\(2\) query, if \(S'\) has an element between \(a_i\) and \(b_i\), the answer is \(0\). Otherwise, it is \(\min(a_i-L,\ R-b_i)\), where \(L\) is the largest element less than \(a_i\) and \(R\) is the smallest element greater than \(b_i\).

You can maintain \(S'\) with std::set or similar data structures to check the existence of an element between \(a_i\) and \(b_i\) and find \(L\) and \(R\) in \(O(\log Q)\) time.

Therefore, the problem can be solved in \(O(Q\log Q)\) time.

posted:
last update: