-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnionFindSet.cpp
More file actions
51 lines (43 loc) · 1.19 KB
/
UnionFindSet.cpp
File metadata and controls
51 lines (43 loc) · 1.19 KB
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
//
// Created by 破忆断回 on 2021/9/26.
//
#include "UnionFindSet.h"
#include <algorithm>
#include<cassert>
using std::vector;
int UnionFindSet::find_father(int val) {
assert(val < m_father.size());
int father_val = m_father[val];
while (m_father[father_val] != father_val) {
father_val = m_father[father_val];
}
m_father[val] = father_val;
return father_val;
}
int UnionFindSet::find_head(int val) {
assert(val < m_father.size());
if (m_father[val] != val)
return find_father(val);
else
return val;
}
UnionFindSet::UnionFindSet(int n) : m_father{vector<int>(n)}, m_count{n} {
int index = 0;
std::for_each(m_father.begin(), m_father.end(), [&index](int &a) { a = index++; });
}
bool UnionFindSet::connected(int a, int b) {
assert(a < m_father.size() && a > 0);
assert(b < m_father.size() && b > 0);
return find_head(a) == find_head(b);
}
void UnionFindSet::merge(int a, int b) {
int father_a = find_father(a);
int father_b = find_father(b);
m_father[father_a] = father_b;
m_father[a] = father_b;
m_father[b] = father_b;
this->m_count--;
}
int UnionFindSet::count() const {
return this->m_count;
}