Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree | C ++ implementation of the approach ; Function to solve queries of the maximum xor value between the nodes in a given level L of a perfect binary tree and a given value X ; Initialize result ; Initialize array to store bits ; Initialize a copy of X and size of array ; Storing the bits of X in the array a [ ] ; Filling the array b [ ] ; Initializing variable which gives maximum xor ; Getting the maximum xor value ; Return the result ; Driver code ; Perform queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN  60 NEW_LINE int solveQuery ( int L , int X ) { int res ; int a [ MAXN ] , b [ L ] ; int ref = X , size_a = 0 ; while ( ref > 0 ) { a [ size_a ] = ref % 2 ; ref /= 2 ; size_a ++ ; } for ( int i = 0 ; i < min ( size_a , L ) ; i ++ ) { if ( a [ i ] == 1 ) b [ i ] = 0 ; else b [ i ] = 1 ; } for ( int i = min ( size_a , L ) ; i < L ; i ++ ) b [ i ] = 1 ; b [ L - 1 ] = 1 ; int temp = 0 , p = 1 ; for ( int i = 0 ; i < L ; i ++ ) { temp += b [ i ] * p ; p *= 2 ; } res = temp ^ X ; return res ; } int main ( ) { int queries [ ] [ 2 ] = { { 2 , 5 } , { 3 , 15 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << solveQuery ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) << endl ; return 0 ; }