-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDisjoint Set Union.cpp
58 lines (52 loc) · 1.27 KB
/
Disjoint Set Union.cpp
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 <bits/stdc++.h>
using namespace std;
/************************************************************************************************/
int const N = 1e5;
int parent[N];
int size[N];
void make(int v) {
parent[v] = v;
size[v] = 1;
}
int find(int v) {
if (parent[v] == v) {
return v;
}
return parent[v] = find(parent[v]);
}
void Union(int a, int b) {
int parentOfa = find(a);
int parentOfb = find(b);
if (parentOfa != parentOfb) {
if (size[a] < size[b]) {
swap(parentOfa, parentOfb);
}
parent[parentOfb] = parentOfa;
size[parentOfa] += size[parentOfb];
}
}
void solve() {
int n, k;
cin >> n >> k;
for (int i = 1; i <= n; i++) {
make(i);
}
while (k--) {
int u, v;
cin >> u >> v;
Union(u, v);
}
int cont = 0;
for (int i = 1; i <= n; i++) {
if (find(i) == i) {
cont++;
}
// cout<<"parent of "<<i<<" is :"<<parent[i]<<endl;
}
cout << cont << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
}