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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
| #include <iostream> #include <vector> #include <algorithm> #include <unordered_map>
using std::cout; using std::endl; using std::pair; using std::sort; using std::unordered_map; using std::vector;
class DisjointSet { public: DisjointSet(const int &e_q_s, const vector<pair<int, int>> &e_r_v) : eq_rel_size(e_q_s), eq_rel_vec(e_r_v) { this->parent_vec.resize(this->eq_rel_size); for (int i = 0; i < this->eq_rel_size; ++i) { parent_vec[i] = i; }
this->depth_vec.resize(this->eq_rel_size, 0);
sort(this->eq_rel_vec.begin(), this->eq_rel_vec.end());
for (const auto &eq_rel_pair : eq_rel_vec) { int first_root = this->find_parent(eq_rel_pair.first); int second_root = this->find_parent(eq_rel_pair.second);
if (first_root == second_root) { continue; } else { if (this->depth_vec[first_root] < this->depth_vec[second_root]) { this->parent_vec[first_root] = second_root; } else if (this->depth_vec[first_root] > this->depth_vec[second_root]) { this->parent_vec[second_root] = first_root; } else { this->parent_vec[second_root] = first_root; ++this->depth_vec[first_root]; } } }
unordered_map<int, vector<int>> root_vec{}; for (int i = 0; i < this->eq_rel_size; ++i) { int root = this->find_parent(i); root_vec[root].push_back(i); }
for (const pair<int, vector<int>> &pair_tree : root_vec) { this->disjoint_set.insert(this->disjoint_set.begin(), pair_tree.second); } }
inline vector<vector<int>> get_disjoint_set() const { return this->disjoint_set; }
inline void print_disjoint_set() const { cout << "并查集: " << endl; for (const vector<int> set : this->disjoint_set) { for (const int num : set) { cout << num << " "; } cout << endl; }
return; }
private: const int eq_rel_size; vector<pair<int, int>> eq_rel_vec;
vector<int> parent_vec; vector<int> depth_vec;
vector<vector<int>> disjoint_set;
int find_parent(int x) {
if (parent_vec[x] != x) { parent_vec[x] = find_parent(parent_vec[x]); }
return parent_vec[x]; } };
int main() { const int eq_rel_size = 9; const vector<pair<int, int>> eq_rel_vec = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {0, 2}, {4, 6}, {0, 8}};
DisjointSet ds(eq_rel_size, eq_rel_vec); ds.print_disjoint_set();
return 0; }
|