-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graphs-DSU.cpp
69 lines (60 loc) · 1.26 KB
/
Graphs-DSU.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
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
using namespace std;
#include <vector>
#include <cmath>
#include <time.h>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <list>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <bits/stdc++.h>
class DSU{
private:
vector<int> parent;
vector<int> size;
public:
DSU(int n){
parent.resize(n+1);
size.resize(n+1);
}
void make(int v){ // adds an independent node
parent[v]= v;
size[v]= 1;
}
int find(int v){// returns the root of v
if(parent[v]==v) return v;
return parent[v]= find(parent[v]);
}
void union_(int a, int b){
a= find(a);
b= find(b);
if(a==b) return;
if(a<b) swap(a, b);
parent[b]= a;
size[a]+= size[b];
}
int getGroupsCount(){
int connectedComponents= 0;
for(int v=1;v<parent.size();v++) if(parent[v]==v) connectedComponents++;
return connectedComponents;
}
};
int main(){
int n, k;
cin>> n>> k;
DSU dsu(n);
for(int i=1;i<=n;i++) dsu.make(i);
while(k--){
int u, v;
cin>> u>> v;
dsu.union_(u, v);
}
cout<< dsu.getGroupsCount();
return 0;
}