Skip to content

Instantly share code, notes, and snippets.

@sandeepkumar-skb
Created January 5, 2021 21:23
Show Gist options
  • Save sandeepkumar-skb/4ff04f4dd65a417747306eac6d190ef4 to your computer and use it in GitHub Desktop.
Save sandeepkumar-skb/4ff04f4dd65a417747306eac6d190ef4 to your computer and use it in GitHub Desktop.
class DSU{
std::vector<int> parent;
std::vector<int> rank;
public:
DSU(int N) : parent(N,0), rank(N,0)
{
for (int i=0; i<N; ++i){
parent[i] = i;
}
}
int find(int node){
if (this->parent[node] != node){
this->parent[node] = find(this->parent[node]);
}
return this->parent[node];
}
bool union_(int node1, int node2){
int p1{find(node1)}, p2{find(node2)};
if (p1 == p2) return false;
if (this->rank[p1] > this->rank[p2]){
this->parent[p2] = p1;
++this->rank[p1];
}
else{
this->parent[p1] = p2;
++this->rank[p2];
}
return true;
}
};
class DSU:
def __init__(self, N):
self.parent = [i for i in range(N)]
self.rank = [0] * N
def find (self, node):
if self.parent[node] != node:
self.parent[node] = self.find(self.parent[node])
return self.parent[node]
def _union(self, node1, node2):
p1,p2 = self.find(node1), self.find(node2)
if p1 != p2:
if self.rank[p1] > self.rank[p2]:
self.parent[p2] = p1
self.rank[p1] += 1
else:
self.parent[p1] = p2
self.rank[p2] += 1
return True
return False
@sandeepkumar-skb
Copy link
Author

sandeepkumar-skb commented Jan 5, 2021

Disjoint-Set Data Structure with rank and path compression.
If N is the number of nodes
Time Complexity : O(N.α(N)) = O(N); O(α(N)) doesn't exceed 4.
Space Complexity : O(N)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment