Example #1
0
int main() {
	DisjointSet<int> a, b;

	assert(setFind(&a) == &a);
	assert(setFind(&b) == &b);

	DisjointSet<int>* c = setUnion(&a, &b);
	assert(c == &a);
}
Example #2
0
DisjointSet<T>*
setFind(DisjointSet<T>* x) {
	if (x->parent == 0)
		return x;

	return x->parent = setFind(x->parent);
}
Example #3
0
int disjointSets::setFind(int p)
{
	//recursivly find p, return root
  if(links[p] == -1)
    return p;
  links[p] = setFind(links[p]);
  return links[p];
}
Example #4
0
DisjointSet<T>*
setUnion(DisjointSet<T>* x, DisjointSet<T>* y) {
	DisjointSet<T> *xRoot, *yRoot;

	xRoot = setFind(x);
	yRoot = setFind(y);
	if (xRoot == yRoot)
		return xRoot;

	if (xRoot->rank < yRoot->rank) {
		xRoot->parent = yRoot;
		return yRoot;
	}
	else if (yRoot->rank < xRoot->rank) {
		yRoot->parent = xRoot;
		return xRoot;
	}
	else {
		yRoot->parent = xRoot;
		xRoot->rank++;
		return xRoot;
	}
}
Example #5
0
 bool validTree(int n, vector<pair<int, int>>& edges) {
     vector<int> pre(n, 0);
     for (int i = 0; i < n; i++) {
         pre[i] = i;
     }
     for (int i = 0; i < edges.size(); i++) {
         setUnion(pre, edges[i].first, edges[i].second);
     }
     int count = 0;
     for (int i = 0; i < n; i++) {
         if (setFind(pre, i) == i) count++;
     }
     return count == 1 && edges.size() == n - 1;
 }
Example #6
0
int
setContains(SET set,void *elt)
{
    return setFind(set,elt) != NULL;
}
Example #7
0
 void setUnion(vector<int>& pre, int x, int y) {
     x = setFind(pre, x);
     y = setFind(pre, y);
     pre[x] = y;
 }
Example #8
0
 int setFind(vector<int>& pre, int x) {
     if (pre[x] != x) {
         pre[x] = setFind(pre, pre[x]);
     }
     return pre[x];
 }