Minimum steps to color the tree with given colors

03 Jun, 2021
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}  
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:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // To store the required answerint ans = 0; // To store the graphvector<int> gr[100005]; // Function to add edgesvoid Add_Edge(int u, int v){    gr[u].push_back(v);    gr[v].push_back(u);} // Dfs functionvoid dfs(int child, int par, int color[]){     // When there is difference in colors    if (color[child] != color[par])        ans++;     // For all it's child nodes    for (auto it : gr[child]) {        if (it == par)            continue;        dfs(it, child, color);    }} // Driver codeint main(){     // Here zero is for parent of node 1    int color[] = { 0, 1, 2, 3, 2, 2, 3 };     // Adding edges in the graph    Add_Edge(1, 2);    Add_Edge(1, 3);    Add_Edge(2, 4);    Add_Edge(2, 5);    Add_Edge(3, 6);     // Dfs call    dfs(1, 0, color);     // Required answer    cout << ans;     return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // To store the required answerstatic int ans = 0; // To store the graphstatic Vector<Vector<Integer>> gr = new Vector<Vector<Integer>>(); // Function to add edgesstatic void Add_Edge(int u, int v){    gr.get(u).add(v);    gr.get(v).add(u);} // Dfs functionstatic void dfs(int child, int par, int color[]){     // When there is difference in colors    if (color[child] != color[par])        ans++;     // For all it's child nodes    for (int i = 0; i < gr.get(child).size(); i++)    {        if (gr.get(child).get(i) == par)            continue;        dfs(gr.get(child).get(i), child, color);    }} // Driver codepublic static void main(String args[]){    for(int i = 0; i <= 10; i++)    gr.add(new Vector<Integer>());     // Here zero is for parent of node 1    int color[] = { 0, 1, 2, 3, 2, 2, 3 };     // Adding edges in the graph    Add_Edge(1, 2);    Add_Edge(1, 3);    Add_Edge(2, 4);    Add_Edge(2, 5);    Add_Edge(3, 6);     // Dfs call    dfs(1, 0, color);     // Required answer    System.out.println( ans);}} // This code is contributed by Arnab Kundu
# Python3 implementation of the approach # To store the required answerans = 0 # To store the graphgr = [[] for i in range(100005)] # Function to add edgesdef Add_Edge(u, v):    gr[u].append(v)    gr[v].append(u) # Dfs functiondef dfs(child, par, color):    global ans     # When there is difference in colors    if (color[child] != color[par]):        ans += 1     # For all it's child nodes    for it in gr[child]:        if (it == par):            continue        dfs(it, child, color)     # Driver code # Here zero is for parent of node 1color = [0, 1, 2, 3, 2, 2, 3] # Adding edges in the graphAdd_Edge(1, 2)Add_Edge(1, 3)Add_Edge(2, 4)Add_Edge(2, 5)Add_Edge(3, 6) # Dfs calldfs(1, 0, color) # Required answerprint(ans) # This code is contributed# by mohit kumar
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{     // To store the required answer    static int ans = 0;         // To store the graph    static List<List<int>> gr = new List<List<int>>();         // Function to add edges    static void Add_Edge(int u, int v)    {        gr[u].Add(v);        gr[v].Add(u);    }         // Dfs function    static void dfs(int child, int par, int []color)    {             // When there is difference in colors        if (color[child] != color[par])            ans++;             // For all it's child nodes        for (int i = 0; i < gr[child].Count; i++)        {            if (gr[child][i] == par)                continue;            dfs(gr[child][i], child, color);        }    }     // Driver code    public static void Main(String []args)    {        for(int i = 0; i <= 10; i++)        gr.Add(new List<int>());             // Here zero is for parent of node 1        int []color = { 0, 1, 2, 3, 2, 2, 3 };             // Adding edges in the graph        Add_Edge(1, 2);        Add_Edge(1, 3);        Add_Edge(2, 4);        Add_Edge(2, 5);        Add_Edge(3, 6);             // Dfs call        dfs(1, 0, color);             // Required answer        Console.WriteLine( ans);    }} // This code has been contributed by 29AjayKumar
<script>// Javascript implementation of the approach // To store the required answerlet ans = 0; // To store the graphlet gr = []; // Function to add edgesfunction Add_Edge(u,v){    gr[u].push(v);    gr[v].push(u);} // Dfs functionfunction dfs(child,par,color){    // When there is difference in colors    if (color[child] != color[par])        ans++;       // For all it's child nodes    for (let i = 0; i < gr[child].length; i++)    {        if (gr[child][i] == par)            continue;        dfs(gr[child][i], child, color);    }} // Driver codefor(let i = 0; i <= 10; i++)    gr.push([]);       // Here zero is for parent of node 1    let color = [ 0, 1, 2, 3, 2, 2, 3 ];       // Adding edges in the graph    Add_Edge(1, 2);    Add_Edge(1, 3);    Add_Edge(2, 4);    Add_Edge(2, 5);    Add_Edge(3, 6);       // Dfs call    dfs(1, 0, color);       // Required answer    document.write( ans);     // This code is contributed by unknown2108</script>
3
 
mohit kumar 29
andrew1234
29AjayKumar
unknown2108
DFS
Graph Coloring
Graph
Mathematical
Tree
Mathematical
DFS
Graph
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Find if there is a path between two vertices in a directed graph
Detect Cycle in a Directed Graph
Introduction to Data Structures
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays