Count distinct median possible for an Array using given ranges of elements | C ++ implementation to Count the number of distinct medians of an array where each array elements are given by a range ; Function to Count the number of distinct medians of an array where each array elements are given by a range ; Loop to store the starting and end range in the array ; Condition to check if the length of the array is odd ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define int  long long int NEW_LINE void solve ( int n , const vector < pair < int , int > > & vec ) { vector < int > a , b ; for ( auto pr : vec ) { a . push_back ( pr . first ) ; b . push_back ( pr . second ) ; } sort ( a . begin ( ) , a . end ( ) ) ; sort ( b . begin ( ) , b . end ( ) ) ; int left , right , ans ; if ( ( n & 1 ) ) { left = a [ n / 2 ] ; right = b [ n / 2 ] ; ans = right - left + 1 ; } else { left = ( a [ n / 2 ] + a [ n / 2 - 1 ] ) ; right = ( b [ n / 2 ] + b [ n / 2 - 1 ] ) ; ans = right - left + 1 ; } cout << ans << endl ; } signed main ( ) { int N = 3 ; vector < pair < int , int > > vec = { { 100 , 100 } , { 10 , 10000 } , { 1 , 1000000000 } } ; solve ( N , vec ) ; return 0 ; }