Answers to: Can any one help me find number of inversions in a 2D array?https://discuss.codechef.com/questions/83919/can-any-one-help-me-find-number-of-inversions-in-a-2d-array<p>I know how to do it using Fenwick tree on a 1D array. If the size of elements is large, I know how to use co-ordinate compression to bring it into workable range. But I am unable to understand how to do it for 2D array. I know about 2D fenwick tree, just not how to use it in this case.</p>
<p>I am referring <a href="https://www.hackerrank.com/contests/morgan-stanley-2016/challenges/matrix-inversions"> this </a> problem.</p>
<p>The solution converts the 2D array into 1D array. After that it uses sorting and then Fenwick tree. This is the part where I am lost. Why use sorting? When we sort, doesn't the relative order of the elements change? </p>
<p>Can someone explain this part with a simple example?</p>
<p>I am trying to follow <em>anudeep2011</em>'s solution.</p>enWed, 10 Aug 2016 22:22:22 +0530Comment by dragonemperor on hemanth_1's answerhttps://discuss.codechef.com/questions/83919/can-any-one-help-me-find-number-of-inversions-in-a-2d-array#83960<p>Thank you bro. After a lot of pen and paper trial and your help, I am finally able to understand. For 1D I always used online algorithm. Never knew it can be done offline like this (eliminates co-ordinate compression). Out of curiosity, can it be solved using online processing? I tried it (after compression), but couldn't solve.</p>
<p>Anyway, thanks a lot :)</p>dragonemperorWed, 10 Aug 2016 22:22:22 +0530https://discuss.codechef.com/questions/83919/can-any-one-help-me-find-number-of-inversions-in-a-2d-array#83960Answer by hemanth_1https://discuss.codechef.com/questions/83919/can-any-one-help-me-find-number-of-inversions-in-a-2d-array/83927<p>Take a 2D BIT, and once the 2D array is converted to a 1D array and is sorted, for each element in the array, starting from the largest, add 1 to BIT [x][y], where x,y are the indices of the element in the original 2D array, after that you find the sum of the values in the BIT within the rectangle (0,0),(x,y), and add it to the answer. I'll tell you why this works, the conditions specified in the problem were : <br>1) x1 <= x2 <br>2) y1<=y2 <br>3) a[x2][y2] < a[x1][y1] <br> By adding the elements starting from the largest, you can say for sure, that any element whose coordinates have been recorded in the 2D BIT, is definitely larger than the current element that you have taken, that takes care of condition 3, and by taking the sum of the rectangle, you're making sure that the conditions 1 and 2 hold true. </p>hemanth_1Mon, 08 Aug 2016 00:50:43 +0530https://discuss.codechef.com/questions/83919/can-any-one-help-me-find-number-of-inversions-in-a-2d-array/83927