int main() { DisjointSet<int> a, b; assert(setFind(&a) == &a); assert(setFind(&b) == &b); DisjointSet<int>* c = setUnion(&a, &b); assert(c == &a); }
DisjointSet<T>* setFind(DisjointSet<T>* x) { if (x->parent == 0) return x; return x->parent = setFind(x->parent); }
int disjointSets::setFind(int p) { //recursivly find p, return root if(links[p] == -1) return p; links[p] = setFind(links[p]); return links[p]; }
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; } }
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; }
int setContains(SET set,void *elt) { return setFind(set,elt) != NULL; }
void setUnion(vector<int>& pre, int x, int y) { x = setFind(pre, x); y = setFind(pre, y); pre[x] = y; }
int setFind(vector<int>& pre, int x) { if (pre[x] != x) { pre[x] = setFind(pre, pre[x]); } return pre[x]; }