i need to create a class of DSU with all its functions how to di it in c++
- User
i need to create a class of DSU with all its functions how to di it in c++
- Assistant
i need to create a class of DSU with all its functions how to di it in c++
To create a Disjoint Set Union (DSU) or Union-Find data structure in C++, you can define a class that implements the main operations: find, union, and often an auxiliary operation like connected. The DSU is typically used to manage a partition of a set into disjoint subsets and is useful in algorithms like Kruskal's Minimum Spanning Tree or finding connected components in a graph.
Here's a step-by-step guide to implementing a basic DSU class:
Data Members:
parent: An array or vector where parent[i] points to the parent of i, or i itself if it is a root of a set.rank: An array or vector to keep track of the tree depth to optimize the union operation.Constructor:
parent and rank arrays/vectors for the elements.Find:
find function with path compression. Path compression helps flatten the structure of the tree whenever find is called, making future operations faster.Union:
union operation with union by rank. This helps in keeping the tree as flat as possible by attaching the smaller tree under the larger tree.Connected (Optional):
Here's a simple implementation example:
#include <vector>
class DSU {
public:
// Constructor: initialize parent and rank vectors
DSU(int n) {
parent.resize(n);
rank.resize(n, 0);
for (int i = 0; i < n; ++i) {
parent[i] = i; // Each element is its own parent
}
}
// Find function with path compression
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // Path compression
}
return parent[x];
}
// Union function with union by rank
void unionSets(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
// Union by rank
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
++rank[rootX];
}
}
}
// Check if two elements are in the same set
bool connected(int x, int y) {
return find(x) == find(y);
}
private:
std::vector<int> parent;
std::vector<int> rank;
};
// Example usage
int main() {
int n = 10; // Number of elements
DSU dsu(n);
dsu.unionSets(0, 1);
dsu.unionSets(1, 2);
dsu.unionSets(3, 4);
if (dsu.connected(0, 2)) {
// Output: 0 and 2 are connected
std::cout << "0 and 2 are connected" << std::endl;
}
if (!dsu.connected(0, 3)) {
// Output: 0 and 3 are not connected
std::cout << "0 and 3 are not connected" << std::endl;
}
return 0;
}
find method, whenever you call find on a node x, you make its root directly point to the root of its set. This reduces the tree height.This implementation ensures that both find and union operations are nearly constant time, specifically (O(\alpha(n))), where (\alpha) is the inverse Ackermann function, which grows very slowly.