Toolbox: Disjoint Sets
Toolbox: Disjoint Sets
What is it?
The disjoint set is a data structure to efficiently implement and run commands to merge sets. They also efficiently implement checking if two items are in the same set without checking the whole set. However, this data structure becomes inefficient when we need to remove nodes.
Code?
int N;
class DSSet
class DSSet
{
private:
int rt[MAXN];
public:
DSSet()
{
for(int i=0; i<N; i++) rt[i] = -1;
}
int root(int n)
{
if(rt[n] < 0) return n;
return (rt[n] = root(rt[n]));
}
void merge(int m, int n)
{
int rm = root(m), rn = root(n);
if(rm == rn) return;
if(rt[rm] > rt[rn]) swap(rm, rn);
rt[rm] += rt[rn];
rt[rn] = rm;
}
int size(int n)
{
return -rt[root(n)];
}
};
Explanation?
- This class is called DSSet. A global variable, N, describes how large the set should be, and should be defined at the time of calling the constructor.
- The function "root" finds the representative for the set containing N, the function's only argument. If two nodes X and Y are in the same set, it's representatives are the same.
- The function "merge" takes nodes M and N, the function's only argument, and points the smaller set's representative to the bigger set's representative. The size of the bigger set is updated. This function does not have any effect if M and N are already in the same set.
- The function "size" gives the size of the set containing node N, including itself.
Comments
Post a Comment