![]() |
VOOZH | about |
Given an integer N, denoting the total number of nodes in a graph without any edges, you have to process Q queries of the form u, v denoting that you have to add an edge between node u and v, after each query you have to print the size difference between largest component and the smallest component of the graph.
Examples:
Input: N = 2, Q = 1, queries = [[1, 2]]
Output: 0
Explanation:
- Initial components = {{1}{2}}
- After query[0]:
- we have components = {{1, 2}}, Since we have only one component of size 2, the difference is 2-2 = 0.
Input: N = 4, Q = 2, queries = [[1, 2],[2, 4]]
Output: [1, 2]
Explanation:
- Initial components = {{1},{2},{3},{4}},
- After query[0]:
- we have components = {{1, 2},{3},{4}} , So difference is, 2-1 = 1.
- After query[1]:
- we have components = {{1, 2, 4},{3}} , So difference is, 3-1 = 2.
Approach: We can use Disjoint-Set-Union(DSU) and Priority Queue(using multiset) to solve this question as discussed below:
For each query of adding an edge between 'u' and 'v' we can use DSU to put both the nodes in the same set and update the size of the set they are in. Now we can put this new size in our multiset and remove the older sizes from it.
Simply print the difference between the maximum and minimum element of the multiset to get the answer for each query.
Firstly we have to construct our DSU functions as per the below steps:
Now use the below algorithm to solve the problem:
below is the implementation of the above algorithm:
1 2
Time Complexity: O(Q(logN) + N), where Q is the number of queries and N is the number of nodes.
Auxiliary Space: O(N), where N is the number of nodes.