Print distinct absolute differences of all possible pairs from a given array | C ++ program for the above approach ; Function to find all distinct absolute difference of all possible pairs of the array ; bset [ i ] : Check if i is present in the array or not ; diff [ i ] : Check if there exists a pair whose absolute difference is i ; Traverse the array , arr [ ] ; Add in bitset ; Iterate over the range [ 0 , Max ] ; If i - th bit is set ; Insert the absolute difference of all possible pairs whose first element is arr [ i ] ; Stores count of set bits ; If there is at least one duplicate element in arr [ ] ; Printing the distinct absolute differences of all possible pairs ; If i - th bit is set ; Driver Code ; Given array ; Given size ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define Max  100005 NEW_LINE void printUniqDif ( int n , int a [ ] ) { bitset < Max > bset ; bitset < Max > diff ; for ( int i = 0 ; i < n ; i ++ ) { bset . set ( a [ i ] ) ; } for ( int i = 0 ; i <= Max ; i ++ ) { if ( bset [ i ] ) { diff = diff | ( bset >> i ) ; } } int X = bset . count ( ) ; if ( X != n ) { cout << 0 << " ▁ " ; } for ( int i = 1 ; i <= Max ; i ++ ) { if ( diff [ i ] ) { cout << i << " ▁ " ; } } } int main ( ) { int a [ ] = { 1 , 4 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printUniqDif ( n , a ) ; return 0 ; }