Minimize deletion of edges to convert Tree into a forest of size at most N/2
Given a tree with N nodes, numbered from 0 to N – 1, the task is to find the minimum number of deletion of edges, such that, the tree is converted into a forest where each tree in the forest can have size less than equal to ⌊N/2⌋.
Input: N = 3, edges = [[0, 1], [0, 2]]
Explanation: The maximum size of each tree after removing the edges can be 1.
So every node has to be separated from each other.
So, remove all the 2 edges present in the tree.
Hence, the answer will be 2.
Input: N = 7, edges = [[0, 1], [1, 2], [1, 3], [0, 4], [4, 5], [4, 6]]
/ \ / \
2 3 5 6
Explanation: Remove the edges (0 – 1) and (0 – 4) to satisfy the condition. Hence, the answer will be 2.
Approach: The idea to solve the problem is using Depth First Search.
Follow the steps to solve the given problem:
- Create the graph from the given input.
- Calculate the centroids using the dfs function.
- If the tree has two centroids, then the answer will be 1.
- Else, declare a vector subtreeSize, which will calculate the subtree size of all the children of the centroid.
- Calculate the subtree sizes using the dfs2 function.
- Declare two variables, ans and sum, to store the answer and the number of nodes removed due to the removal of edges.
- Sort the subtreeSize in descending order.
- Iterate over the subtreeSize vector.
- Add the current value to the sum and increase the ans by 1.
- If the remaining nodes are less than or equal to N/ 2
- Break the loop.
- Finally, return the ans.
Below is the implementation of the above approach :
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Please Login to comment...