Find the node whose sum with X has maximum set bits | Javascript implementation of the approach ; number of set bits ; Function to perform dfs to find the maximum value ; If current set bits value is greater than the current maximum ; If count is equal to the maximum then choose the node with minimum value ; Driver code ; Weights of the node ; Edges of the tree
let maximum = Number . MIN_VALUE , x , ans = Number . MAX_VALUE ; let graph = new Array ( 100 ) ; for ( let i = 0 ; i < 100 ; i ++ ) { graph [ i ] = [ ] ; } let weight = [ ] ; function __builtin_popcount ( x ) { let c = 0 ; for ( let i = 0 ; i < 60 ; i ++ ) if ( ( ( x >> i ) & 1 ) != 0 ) c ++ ; return c ; } function dfs ( node , parent ) { let a = __builtin_popcount ( weight [ node ] + x ) ; if ( maximum < a ) { maximum = a ; ans = node ; } else if ( maximum == a ) ans = Math . min ( ans , node ) ; for ( let i = 0 ; i < graph [ node ] . length ; i ++ ) { if ( graph [ node ] [ i ] == parent ) continue ; dfs ( graph [ node ] [ i ] , node ) ; } } x = 15 ; weight . push ( 0 ) ; weight . push ( 5 ) ; weight . push ( 10 ) ; ; weight . push ( 11 ) ; ; weight . push ( 8 ) ; weight . push ( 6 ) ; graph [ 1 ] . push ( 2 ) ; graph [ 2 ] . push ( 3 ) ; graph [ 2 ] . push ( 4 ) ; graph [ 1 ] . push ( 5 ) ; dfs ( 1 , 1 ) ; document . write ( ans ) ;