📜  门| GATE CS 2021 |设置 2 |问题 26(1)

📅  最后修改于: 2023-12-03 15:42:12.944000             🧑  作者: Mango

GATE CS 2021 SET 2 QUESTION 26

Introduction

The GATE CS 2021 SET 2 QUESTION 26 is a programming question that requires the implementation of a data structure called "Disjoint Set Union". This data structure is used to maintain a collection of disjoint sets, each containing a set of elements.

Problem Description

The problem statement requires the implementation of the following two operations on the Disjoint Set Union data structure:

  • union(x, y): Merge the sets containing elements x and y. If x and y are already in the same set, do nothing.

  • find(x): Find the set containing element x.

The implementation should use the path compression and union by rank optimizations to achieve a time complexity of O(alpha(n)) per operation, where alpha(n) is the inverse Ackermann function.

Implementation

Here is the Python implementation of the Disjoint Set Union data structure:

class DisjointSetUnion:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n
    
    def find(self, x):
        if x != self.parent[x]:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    
    def union(self, x, y):
        px, py = self.find(x), self.find(y)
        if px == py:
            return
        if self.rank[px] < self.rank[py]:
            px, py = py, px
        self.parent[py] = px
        if self.rank[px] == self.rank[py]:
            self.rank[px] += 1

The DisjointSetUnion class has two instance variables: parent and rank. The parent array is used to store the parent of each element in the disjoint sets. Initially, each element is its own parent. The rank array is used to store the rank of each set. Initially, each rank is 0.

The find method finds the parent of the set containing the element x. It also performs path compression by updating the parent of each visited element to the root of the set.

The union method merges the sets containing the elements x and y. It first finds the parents of the two sets using find. If the parents are the same, the operation does nothing. Otherwise, it merges the two sets by making the parent of the set with lower rank the child of the parent of the set with higher rank. It also updates the rank of the parent of the merged set if necessary.

Conclusion

The Disjoint Set Union data structure is a useful tool for maintaining a collection of disjoint sets. The implementation provided in this article uses path compression and union by rank optimizations to achieve a time complexity of O(alpha(n)) per operation.