Find the node whose sum with X has maximum set bits | Python implementation of the approach ; Function to perform dfs to find the maximum set bits 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
from sys import maxsize NEW_LINE maximum , x , ans = - maxsize , None , maxsize NEW_LINE graph = [ [ ] for i in range ( 100 ) ] NEW_LINE weight = [ 0 ] * 100 NEW_LINE def dfs ( node , parent ) : NEW_LINE INDENT global x , ans , graph , weight , maximum NEW_LINE a = bin ( weight [ node ] + x ) . count ( '1' ) NEW_LINE if maximum < a : NEW_LINE INDENT maximum = a NEW_LINE ans = node NEW_LINE DEDENT elif maximum == a : NEW_LINE INDENT ans = min ( ans , node ) NEW_LINE DEDENT for to in graph [ node ] : NEW_LINE INDENT if to == parent : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( to , node ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 15 NEW_LINE weight [ 1 ] = 5 NEW_LINE weight [ 2 ] = 10 NEW_LINE weight [ 3 ] = 11 NEW_LINE weight [ 4 ] = 8 NEW_LINE weight [ 5 ] = 6 NEW_LINE graph [ 1 ] . append ( 2 ) NEW_LINE graph [ 2 ] . append ( 3 ) NEW_LINE graph [ 2 ] . append ( 4 ) NEW_LINE graph [ 1 ] . append ( 5 ) NEW_LINE dfs ( 1 , 1 ) NEW_LINE print ( ans ) NEW_LINE DEDENT