We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
A solution built on these lines passed all test cases:
Perform a depth-first search preprocessing step on the tree starting at the root (which is actually specified in the input). When first encountering a node, create a colour set that will contain all the colours in the subtree rooted at that node, add the colour of the node to this set, then process each child of the node.
Whenever you finish processing a node:
Record the size of its colour set - this record will be used for answering queries.
If its colour set is bigger than its parent's colour set so far, switch the two sets, because it's more efficient to add elements from a smaller set to a larger one than vice versa.
Add each element in the child's colour set to the parent's colour set.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Coloring Tree
You are viewing a single comment's thread. Return to all comments →
A solution built on these lines passed all test cases:
Perform a depth-first search preprocessing step on the tree starting at the root (which is actually specified in the input). When first encountering a node, create a colour set that will contain all the colours in the subtree rooted at that node, add the colour of the node to this set, then process each child of the node.
Whenever you finish processing a node: