**Problem Link:**

[Contest][1]

[Practice][2]

**Author and Editorialist:** [sumeet-varma][3]

**Difficulty:** Medium

**Pre-requisites:** - Segment tree

**Problem**: Given *N* intervals*(L*, R*)*, you have to minimize the magic for *Q* queries where each query has two parameters *A* and *B* and magic is calculated as follows.

magic = 0

for i in range(0, N)

x = choose any point which lies in i^{th} interval (x ≥ L* and x ≤ R*)

y = choose A or B

magic += |x – y|

**Explanation:**

For a given query *(A <= B)*, intervals having non-zero magic can be split in 3 different categories.

*Case 1: L* <= R* <= A
Case 2: A < L* <= R* < B
Case 3: B < L* <= R**

For case 1, *magic += A - R**. It can be solved in *O(logn)* per query after sorting the intervals on end point and building range sum segment tree/BIT over it. Case 3 can be solved in a similar way.

For case 2,

*Lemma: If (L + R*) <= (A + B) , then magic += L* - A else magic += B - R***

Proof: Let magic += L* - A

herefore min(L* - A, B - R*) = L* - A

\implies L* - A \le B - R*

\implies L* + R* \le A + B

Intuitive Proof: If *midpoint([L*, R*]) \le midpoint([A, B])*, then *L** should be closer to A than *R** is from B.

Thus, we again split the intervals of case 3 in two types.

*Case 3A: A < L* <= R* < B and L* + R* <= A + B*

*Case 3B: A < L* <= R* < B and L* + R* > A + B*

For case 3A, we * sort the intervals based on L + R*** and build a segment tree over it in which in each node, we again sort the intervals based on

*L**and also build a prefix sum over sorted

*L**in each node.

For each query, we find \sum *L** and count of all intervals such that *L* > A* and *L* + R* <= A + B*. We don’t need to check for R* < B. Think why?

This can be done with the help of binary search on array of sorted intervals for determining prefix of intervals having *L* + R* <= A + B* and then a range query in segment tree for that prefix.

And finally, *magic += \sum L* - count * A*

Case 3B can be solved in a similar way.

Time Complexity: O((N + Q) * log^2N)

Space Complexity: O(N * log^2N)

[1]: https://www.codechef.com/IPC15FLB/problems/MINMAGIC

[2]: https://www.codechef.com/problems/MINMAGIC

[3]: https://www.codechef.com/users/sumeet_varma