Minimum steps to color the tree with given colors | To store the required answer ; To store the graph ; Function to add edges ; Dfs function ; When there is difference in colors ; For all it 's child nodes ; Here zero is for parent of node 1 ; Adding edges in the graph ; Dfs call ; Required answer
ans = 0 NEW_LINE gr = [ [ ] for i in range ( 100005 ) ] NEW_LINE def Add_Edge ( u , v ) : NEW_LINE INDENT gr [ u ] . append ( v ) NEW_LINE gr [ v ] . append ( u ) NEW_LINE DEDENT def dfs ( child , par , color ) : NEW_LINE INDENT global ans NEW_LINE if ( color [ child ] != color [ par ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT for it in gr [ child ] : NEW_LINE INDENT if ( it == par ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( it , child , color ) NEW_LINE DEDENT DEDENT color = [ 0 , 1 , 2 , 3 , 2 , 2 , 3 ] NEW_LINE Add_Edge ( 1 , 2 ) NEW_LINE Add_Edge ( 1 , 3 ) NEW_LINE Add_Edge ( 2 , 4 ) NEW_LINE Add_Edge ( 2 , 5 ) NEW_LINE Add_Edge ( 3 , 6 ) NEW_LINE dfs ( 1 , 0 , color ) NEW_LINE print ( ans ) NEW_LINE