![]() |
VOOZH | about |
Given a tree with N nodes which initially have no color and an array color[] of size N which represent the color of each node after the coloring process takes place. The task is to color the tree into the given colors using the smallest possible number of steps. On each step, one can choose a vertex v and a color x, and then color all vertices in the sub-tree of v (including v itself) with color x. Note that root is vertex number 1.
Examples:
Input: color[] = { 1, 1, 2, 1, 3, 1}
👁 Image
👁 Image
Output: 4
Color the sub-tree rooted at node 1 with color 1.
Then all the vertices have colors 1.
Now, color the sub-tree rooted at 3 with color 2.
Finally, color the sub-trees rooted at 5 and 6 with colors 3 and 1 respectively.
Input: color[] = { 1, 2, 3, 2, 2, 3}
Output: 3
Approach: Call a DFS function at vertex 1 and initially keep answer as zero. Increment the answer whenever there is a difference in colors of child and parent nodes.
See the below code for better understanding.
Below is the implementation of the above approach:
3