Maximum Bitwise XOR of node values of an Acyclic Graph made up of N given vertices using M edges | C ++ program for the above approach ; Function to find the maximum Bitwise XOR of any subset of the array of size K ; Number of node must K + 1 for K edges ; Stores the maximum Bitwise XOR ; Generate all subsets of the array ; __builtin_popcount ( ) returns the number of sets bits in an integer ; Initialize current xor as 0 ; If jth bit is set in i then include jth element in the current xor ; Update the maximum Bitwise XOR obtained so far ; Return the maximum XOR ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumXOR ( int arr [ ] , int n , int K ) { K ++ ; int maxXor = INT_MIN ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { if ( __builtin_popcount ( i ) == K ) { int cur_xor = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( i & ( 1 << j ) ) cur_xor = cur_xor ^ arr [ j ] ; } maxXor = max ( maxXor , cur_xor ) ; } } return maxXor ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int M = 2 ; cout << maximumXOR ( arr , N , M ) ; return 0 ; }