Count number of subsets whose median is also present in the same subset | C ++ implementation of the approach ; Function to store pascal triangle in 2 - d array ; Function to return a raised to the power n with complexity O ( log ( n ) ) ; Function to return the number of sub - sets whose median is also present in the set ; Number of odd length sub - sets ; Sort the array ; Checking each element for leftmost middle element while they are equal ; Calculate the number of elements in right of rightmost middle element ; Calculate the number of elements in left of leftmost middle element ; Add selected even length subsets to the answer ; Driver code
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; long long mod = 1000000007 ; long long arr [ 1001 ] [ 1001 ] ; void Preprocess ( ) { arr [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= 1000 ; ++ i ) { arr [ i ] [ 0 ] = 1 ; for ( int j = 1 ; j < i ; ++ j ) { arr [ i ] [ j ] = ( arr [ i - 1 ] [ j - 1 ] + arr [ i - 1 ] [ j ] ) % mod ; } arr [ i ] [ i ] = 1 ; } } long long powmod ( long long a , long long n ) { if ( ! n ) return 1 ; long long pt = powmod ( a , n / 2 ) ; pt = ( pt * pt ) % mod ; if ( n % 2 ) return ( pt * a ) % mod ; else return pt ; } long long CountSubset ( int * val , int n ) { long long ans = powmod ( 2 , n - 1 ) ; sort ( val , val + n ) ; for ( int i = 0 ; i < n ; ++ i ) { int j = i + 1 ; while ( j < n && val [ j ] == val [ i ] ) { int r = n - 1 - j ; int l = i ; ans = ( ans + arr [ l + r ] [ l ] ) % mod ; j ++ ; } } return ans ; } int main ( ) { Preprocess ( ) ; int val [ ] = { 2 , 3 , 2 } ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; cout << CountSubset ( val , n ) << endl ; return 0 ; }