The Wayback Machine - https://web.archive.org/web/20250415193305/https://www.geeksforgeeks.org/maximum-edge-removal-tree-make-even-forest/
Open In App

Maximum edge removal from tree to make even forest

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a tree with n nodes where n is even. The tree is numbered from 1 to n, has n – 1 edges and is rooted at node 1. The task is to eliminate the maximum number of edges resulting in a set of disjoint trees where the number of nodes in each tree is divisible by 2.

Examples: 

Input: n = 10, edges = [[2, 1], [3, 1], [4, 3], [5, 2], [6, 1], [7, 2], [8, 6], [9, 8], [10, 8]]
Output: 2
Explanation:

Original tree:

maximum---------edge---------removal---------from---------tree---------to---------make---------even---------forest---------1


After removing edge 1-3 and 1-6, each remaining component consists of even number of nodes.

maximum---------edge---------removal---------from---------tree---------to---------make---------even---------forest---------2


Input: n = 4, edges = [[2, 1], [4, 2], [1, 3]]
Output: 1
Explanation:

Original tree:

maximum---------edge---------removal---------from---------tree---------to---------make---------even---------forest---------3


After removing edge 1-2, each remaining component consists of even number of nodes.

maximum---------edge---------removal---------from---------tree---------to---------make---------even---------forest---------4

Approach:

The idea is to use a depth-first search (DFS) to traverse the tree and calculate the size of each subtree. If a subtree has an even number of nodes, the edge connecting it to its parent can be removed. During the traversal, we count such removable edges. This ensures that the tree remains disconnected in the desired way.

C++
// C++ program to calculate the maximum number of edges
// that can be removed to make the graph disconnected
#include <bits/stdc++.h>
using namespace std;

int dfs(int vertex, vector<bool>& visited, 
          vector<vector<int>>& adj, int& res) {

    // Initialize count of nodes in the current subtree
    int count = 0;

    // Mark the current vertex as visited
    visited[vertex] = true;

    // Iterate through all adjacent vertices
    for (auto neighbor : adj[vertex]) {
      
        // If the neighbor is not visited, perform DFS
        if (!visited[neighbor]) {
            int subtreeNodes = dfs(neighbor, 
                                   visited, adj, res);
            
            // Check if the subtree has an even number
            // of nodes
            if (subtreeNodes % 2 == 0) {
                res++; 
            } 
            else {
                count += subtreeNodes;
            }
        }
    }

    // Return the total number of nodes in the subtree
    return count + 1;
}

int maxEdgeRemoval(int n, vector<vector<int>>& edges) {

    // Adjacency list representation of the graph
    vector<vector<int>> adj(n);

    // Visited array to track visited vertices
    vector<bool> visited(n, false);

    // Fill the adjacency list
    for (auto edge : edges) {
        adj[edge[0] - 1].push_back(edge[1] - 1);
        adj[edge[1] - 1].push_back(edge[0] - 1);
    }

    // Variable to store the count of removable edges
    int res = 0;

    // Perform DFS starting from the root vertex (0)
    dfs(0, visited, adj, res);

    return res;
}

int main() {

    int n = 6;
    vector<vector<int>> edges = {
        {2, 1}, {4, 2}, {1, 3}
    };

    cout << maxEdgeRemoval(n, edges) << endl;

    return 0;
}
Java
// Java program to calculate the maximum number of edges
// that can be removed to make the graph disconnected
import java.util.*;

class GfG {

    static int dfs(int vertex, boolean[] visited, 
                   List<List<Integer>> adj, int[] res) {

        // Initialize count of nodes in the current subtree
        int count = 0;

        // Mark the current vertex as visited
        visited[vertex] = true;

        // Iterate through all adjacent vertices
        for (int neighbor : adj.get(vertex)) {
            
            // If the neighbor is not visited, perform DFS
            if (!visited[neighbor]) {
                int subtreeNodes = dfs(neighbor, 
                                       visited, adj, res);

                // Check if the subtree has an even number
                // of nodes
                if (subtreeNodes % 2 == 0) {
                    res[0]++; 
                } 
                else {
                    count += subtreeNodes;
                }
            }
        }

        // Return the total number of nodes in the subtree
        return count + 1;
    }

    static int maxEdgeRemoval(int n, int[][] edges) {

        // Adjacency list representation of the graph
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<>());
        }

        // Visited array to track visited vertices
        boolean[] visited = new boolean[n];

        // Fill the adjacency list
        for (int[] edge : edges) {
            adj.get(edge[0] - 1).add(edge[1] - 1);
            adj.get(edge[1] - 1).add(edge[0] - 1);
        }

        // Variable to store the count of removable edges
        int[] res = {0};

        // Perform DFS starting from the root vertex (0)
        dfs(0, visited, adj, res);

        return res[0];
    }

    public static void main(String[] args) {

        int n = 6;
        int[][] edges = {
            {2, 1}, {4, 2}, {1, 3}
        };

        System.out.println(maxEdgeRemoval(n, edges));
    }
}
Python
# Python program to calculate the maximum number of edges
# that can be removed to make the graph disconnected
from typing import List

def dfs(vertex: int, visited: List[bool], 
        adj: List[List[int]], res: List[int]) -> int:

    # Initialize count of nodes in the current subtree
    count = 0

    # Mark the current vertex as visited
    visited[vertex] = True

    # Iterate through all adjacent vertices
    for neighbor in adj[vertex]:

        # If the neighbor is not visited, perform DFS
        if not visited[neighbor]:
            subtree_nodes = dfs(neighbor, visited, adj, res)

            # Check if the subtree has an even number
            # of nodes
            if subtree_nodes % 2 == 0:
                res[0] += 1
            else:
                count += subtree_nodes

    # Return the total number of nodes in the subtree
    return count + 1

def maxEdgeRemoval(n: int, edges: List[List[int]]) -> int:

    # Adjacency list representation of the graph
    adj = [[] for _ in range(n)]

    # Visited array to track visited vertices
    visited = [False] * n

    # Fill the adjacency list
    for edge in edges:
        u, v = edge[0] - 1, edge[1] - 1
        adj[u].append(v)
        adj[v].append(u)

    # Variable to store the count of removable edges
    res = [0]

    # Perform DFS starting from the root vertex (0)
    dfs(0, visited, adj, res)

    return res[0]

if __name__ == "__main__":
  
    n = 6
    edges = [
        [2, 1], [4, 2], [1, 3]
    ]

    print(maxEdgeRemoval(n, edges))
C#
// C# program to calculate the maximum number of edges
// that can be removed to make the graph disconnected
using System;
using System.Collections.Generic;

class GfG {

    static int DFS(int vertex, bool[] visited, 
                   List<List<int>> adj, ref int res) {

        // Initialize count of nodes in the current subtree
        int count = 0;

        // Mark the current vertex as visited
        visited[vertex] = true;

        // Iterate through all adjacent vertices
        foreach (int neighbor in adj[vertex]) {

            // If the neighbor is not visited, perform DFS
            if (!visited[neighbor]) {
                int subtreeNodes = DFS(neighbor, 
                                       visited, adj, ref res);

                // Check if the subtree has an even number
                // of nodes
                if (subtreeNodes % 2 == 0) {
                    res++;
                } 
                else {
                    count += subtreeNodes;
                }
            }
        }

        // Return the total number of nodes in the subtree
        return count + 1;
    }

    static int MaxEdgeRemoval(int n, int[,] edges) {

        // Adjacency list representation of the graph
        List<List<int>> adj = new List<List<int>>();
        for (int i = 0; i < n; i++) {
            adj.Add(new List<int>());
        }

        // Visited array to track visited vertices
        bool[] visited = new bool[n];

        // Fill the adjacency list
        int edgeCount = edges.GetLength(0);
        for (int i = 0; i < edgeCount; i++) {
            int u = edges[i, 0] - 1;
            int v = edges[i, 1] - 1;
            adj[u].Add(v);
            adj[v].Add(u);
        }

        // Variable to store the count of removable edges
        int res = 0;

        // Perform DFS starting from the root vertex (0)
        DFS(0, visited, adj, ref res);

        return res;
    }

    static void Main() {

        int n = 6;
        int[,] edges = {
            {2, 1}, {4, 2}, {1, 3}
        };

        Console.WriteLine(MaxEdgeRemoval(n, edges));
    }
}
JavaScript
// JavaScript program to calculate the maximum number of edges
// that can be removed to make the graph disconnected

function dfs(vertex, visited, adj, res) {

    // Initialize count of nodes in the current subtree
    let count = 0;

    // Mark the current vertex as visited
    visited[vertex] = true;

    // Iterate through all adjacent vertices
    for (let neighbor of adj[vertex]) {

        // If the neighbor is not visited, perform DFS
        if (!visited[neighbor]) {
            let subtreeNodes = dfs(neighbor, visited, adj, res);

            // Check if the subtree has an even number
            // of nodes
            if (subtreeNodes % 2 === 0) {
                res.count += 1;
            } else {
                count += subtreeNodes;
            }
        }
    }

    // Return the total number of nodes in the subtree
    return count + 1;
}

function maxEdgeRemoval(n, edges) {

    // Adjacency list representation of the graph
    let adj = Array.from({ length: n }, () => []);

    // Visited array to track visited vertices
    let visited = Array(n).fill(false);

    // Fill the adjacency list
    for (let edge of edges) {
        let u = edge[0] - 1, v = edge[1] - 1;
        adj[u].push(v);
        adj[v].push(u);
    }

    // Variable to store the count of removable edges
    let res = { count: 0 };

    // Perform DFS starting from the root vertex (0)
    dfs(0, visited, adj, res);

    return res.count;
}

let n = 6;
let edges = [
    [2, 1], [4, 2], [1, 3]
];

console.log(maxEdgeRemoval(n, edges));

Output
1

Time Complexity: O(n), as we are traversing every node only once, where n is the number of nodes.
Auxilairy Space: O(n), as space is used for the adjacency list and the visited array, proportional to the number of nodes.



Next Article
Article Tags :
Practice Tags :

Similar Reads