Mo's Algorithm - Introduction
Hello everyone !
Today , we will be learning about Mo's Algorithm's introduction via a simple problem .
Welcome back to my blog .
Today , we will be learning about Mo's Algorithm's introduction via a simple problem .
In this problem we are given an array of n numbers and then we are given q queries consiting of l and r and we need to find the sum of elements from l to r.
We could do this naively , by just summing up all elements from l to r and then printing this .
But the time complexity of this naive method would be O(m*q) .
But what if we played smartly , we are given all queries so why not pre process them .
So , let us sort the queries into blocks with l in the range 0 to root(n) then to 2*root(n) and so on .
And in each block , let us sort the queries with r.
Then we iterate over all the queries and we subtract the elements not required and add the elements required from the previous sum thus reducing our work .
The time complexity of this program would be O((n+q)*root(n)) , which is quite better than before .
This time complexity can be found out easily by computing the number of movements of the left and right cursors in recomputing the sum .
Do take a look at the below C++ code for better understanding :-
Code :-
Comments
Post a Comment