Count inversions in an array | Set 3 ( Using BIT ) | C ++ program to count inversions using Binary Indexed Tree ; Returns sum of arr [ 0. . index ] . This function assumes that the array is preprocessed and partial sums of array elements are stored in BITree [ ] . ; Traverse ancestors of BITree [ index ] ; Add current element of BITree to sum ; Move index to parent node in getSum View ; Updates a node in Binary Index Tree ( BITree ) at given index in BITree . The given value ' val ' is added to BITree [ i ] and all of its ancestors in tree . ; Traverse all ancestors and add ' val ' ; Add ' val ' to current node of BI Tree ; Update index to that of parent in update View ; Converts an array to an array with values from 1 to n and relative order of smaller and greater elements remains same . For example , { 7 , - 90 , 100 , 1 } is converted to { 3 , 1 , 4 , 2 } ; Create a copy of arrp [ ] in temp and sort the temp array in increasing order ; Traverse all array elements ; lower_bound ( ) Returns pointer to the first element greater than or equal to arr [ i ] ; Returns inversion count arr [ 0. . n - 1 ] ; Convert arr [ ] to an array with values from 1 to n and relative order of smaller and greater elements remains same . For example , { 7 , - 90 , 100 , 1 } is converted to { 3 , 1 , 4 , 2 } ; Create a BIT with size equal to maxElement + 1 ( Extra one is used so that elements can be directly be used as index ) ; Traverse all elements from right . ; Get count of elements smaller than arr [ i ] ; Add current element to BIT ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getSum ( int BITree [ ] , int index ) { while ( index > 0 ) { sum += BITree [ index ] ; index -= index & ( - index ) ; } return sum ; } void updateBIT ( int BITree [ ] , int n , int index , int val ) { while ( index <= n ) { BITree [ index ] += val ; index += index & ( - index ) ; } } void convert ( int arr [ ] , int n ) { int temp [ n ] ; for ( int i = 0 ; i < n ; i ++ ) temp [ i ] = arr [ i ] ; sort ( temp , temp + n ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = lower_bound ( temp , temp + n , arr [ i ] ) - temp + 1 ; } } int getInvCount ( int arr [ ] , int n ) { convert ( arr , n ) ; int BIT [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) BIT [ i ] = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { invcount += getSum ( BIT , arr [ i ] - 1 ) ; updateBIT ( BIT , n , arr [ i ] , 1 ) ; } return invcount ; } int main ( ) { int arr [ ] = { 8 , 4 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << " Number ▁ of ▁ inversions ▁ are ▁ : ▁ " << getInvCount ( arr , n ) ; return 0 ; }