forked from csfx-py/hacktober2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdsu.cpp
More file actions
44 lines (41 loc) · 800 Bytes
/
dsu.cpp
File metadata and controls
44 lines (41 loc) · 800 Bytes
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
void make_set(int v) {
parent[v] = v;
size[v] = 1;
}
int find_set(int v) {
if (v == parent[v])
return v;
return parent[v] = find_set(parent[v]);
}
void union_sets(int a, int b) {
a = find_set(a);
b = find_set(b);
if (a != b) {
if (size[a] < size[b])
swap(a, b);
parent[b] = a;
size[a] += size[b];
}
}
int main () {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
make_set(i);
}
int m;
cin >> m;
for (int i = 1; i <= m; ++i) {
int u, v;
cin >> u >> v;
union_sets(u, v);
}
int ans = 0; // no of sets
set<int> s;
for (int i = 1; i <= n; ++i) {
s.insert(find_set(i));
}
ans = (int) s.size();
cout << ans << '\n';
return 0;
}