1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| class UnionFind { private: int count; vector<int> size; vector<int> parent; public: UnionFind(int n) : count(n) { parent.resize(n); size.resize(n); for (int i = 0; i < n; ++i) { parent[i] = i; size[i] = 1; } } int Count() { return count; } int findRoot (int x) { while (x != parent[x]) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; } void unionIt(int p, int q) { int rootP = findRoot(p); int rootQ = findRoot(q); if (rootP == rootQ) return; if (size[rootP] >= size[rootQ]) { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } else { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } --count; } bool isConnected(int p, int q) { int rootP = findRoot(p); int rootQ = findRoot(q); if (rootP == rootQ) return true; else return false; } };
|