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 58
| #include<iostream> #include<vector> #include<cstring> #include<cstdio> using namespace std; class DisjSets { public: explicit DisjSets(int numElements);
int find(int x) const; int find(int x); void unionSets(int root1, int root2);
private: vector<int> s; }; DisjSets::DisjSets(int numElements) :s{ numElements,-1 } { }
int DisjSets::find(int x) { if (s[x] < 0) { return x; } else { return s[x] = find(s[x]); } }
void DisjSets::unionSets(int root1, int root2) { if (s[root2] < s[root1]) s[root1] = root2; else { if (s[root1] == s[root2]) --s[root1]; s[root2] = root1; } }
|