Disjoint Sets Data Structure (Disjoint Sets)
More...
#include <iostream>
#include <vector>
Disjoint Sets Data Structure (Disjoint Sets)
- Author
- leoyang429
A disjoint set data structure (also called union find or merge find set) is a data structure that tracks a set of elements partitioned into a number of disjoint (non-overlapping) subsets. Some situations where disjoint sets can be used are- to find connected components of a graph, kruskal's algorithm for finding Minimum Spanning Tree etc. There are two operation which we perform on disjoint sets - 1) Union 2) Find
◆ CreateSet()
Function to create a set
- Parameters
-
40 for (
int i = 1; i <= n; ++i) {
◆ Find()
Find operation takes a number x and returns the set to which this number belongs to.
- Parameters
-
- Returns
- set to which x belongs to
57 return root[x] =
Find(root[x]);
◆ InSameUnion()
bool InSameUnion |
( |
int |
x, |
|
|
int |
y |
|
) |
| |
A utility function to check if x and y are from same set or not
- Parameters
-
x | element of some set |
y | element of some set |
◆ main()
Main function
97 for (
int i = 1; i <= 100; ++i) {
104 cout <<
"1 and 2 are initially not in the same subset" <<
endl;
109 cout <<
"1 and 2 are now in the same subset" <<
endl;
◆ Union()
void Union |
( |
int |
x, |
|
|
int |
y |
|
) |
| |
Union operation combines two disjoint sets to make a single set in this union function we pass two elements and check if they are from different sets then combine those sets
- Parameters
-
x | element of some set |
y | element of some set |
81 if (rank[a] < rank[b]) {
83 }
else if (rank[a] > rank[b]) {