We have an array of integer and we want at evey odd index i we have to find sum of first i/2 smallest number from index 1 to index i
lets
At index 1 sum of 0 smallest number
At index 3 sum of first one smallest number
At index 5 sum of first two smallest number
At index 7 sum of first three smallest number
At index 9 sum of first four smallest number
and so on.
any solution/Idea in o(n) or o(nLogn) ?
plzz explain that code just introduction
This can be solved without any special data structure. Assume $$$0$$$ based indexing. At index $$$i$$$ you want $$$\lfloor \frac{i}{2} \rfloor$$$ smallest numbers.
You can maintain two multisets $$$\texttt{S}$$$ and $$$\texttt{B}$$$. In $$$\texttt{S}$$$ we will be store smaller numbers while in $$$\texttt{B}$$$ we will store the bigger elements More formally, minimum element of $$$\texttt{B}$$$ should be greater than equal to maximum element of $$$\texttt{S}$$$.
If you notice carefully then you will see that we want to keep lengths of $$$\texttt{S}$$$ and $$$\texttt{B}$$$ as close as possible with $$$\texttt{B}$$$ having bigger size than $$$\texttt{S}$$$ if you cannot keep the sizes equal. At each step you can decide whether you want to put element in $$$\texttt{S}$$$ or $$$\texttt{B}$$$ by first filling the multiset with smaller size and then until you find $$$\textbf{Maximum element of}$$$ $$$\texttt{S}$$$ > $$$\textbf{Minimum element of}$$$ $$$\texttt{B}$$$. You can keep track of the sum of elements present in $$$\texttt{S}$$$ easily.
Thanks
We first convert the numbers to their orders, then find which order corresponds to the i/2 th element, then get the sum of all numbers < that number (from the orders) in the first i+1 elements of the array (some orders are not filled yet, so the value is 0) (Since the query() function processes half-intervals, its "<" and not "<=" as expected).
Thanks it was helpful.
https://www.codechef.com/viewsolution/1060437598
You can see solution, it's the same problem
Thanks