text: Count quadruples of given type from given array | C ++ program of the above approach ; lcount [ i ] [ j ] : Stores the count of i on left of index j ; rcount [ i ] [ j ] : Stores the count of i on right of index j ; Function to count unique elements on left and right of any index ; Find the maximum array element ; Calculate prefix sum of counts of each value ; Calculate suffix sum of counts of each value ; Function to count quadruples of the required type ; Driver Code
code: #include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; const int maxN = 2002 ; int lcount [ maxN ] [ maxN ] ; int rcount [ maxN ] [ maxN ] ; void fill_counts ( int a [ ] , int n ) { int i , j ; int maxA = a [ 0 ] ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] > maxA ) { maxA = a [ i ] ; } } memset ( lcount , 0 , sizeof ( lcount ) ) ; memset ( rcount , 0 , sizeof ( rcount ) ) ; for ( i = 0 ; i < n ; i ++ ) { lcount [ a [ i ] ] [ i ] = 1 ; rcount [ a [ i ] ] [ i ] = 1 ; } for ( i = 0 ; i <= maxA ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { lcount [ i ] [ j ] = lcount [ i ] [ j - 1 ] + lcount [ i ] [ j ] ; } for ( j = n - 2 ; j >= 0 ; j -- ) { rcount [ i ] [ j ] = rcount [ i ] [ j + 1 ] + rcount [ i ] [ j ] ; } } } int countSubsequence ( int a [ ] , int n ) { int i , j ; fill_counts ( a , n ) ; int answer = 0 ; for ( i = 1 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n - 1 ; j ++ ) { answer += lcount [ a [ j ] ] [ i - 1 ] * rcount [ a [ i ] ] [ j + 1 ] ; } } return answer ; } int main ( ) { int a [ 7 ] = { 1 , 2 , 3 , 2 , 1 , 3 , 2 } ; cout << countSubsequence ( a , 7 ) ; return 0 ; }