-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path323.cpp
More file actions
49 lines (45 loc) · 951 Bytes
/
323.cpp
File metadata and controls
49 lines (45 loc) · 951 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
45
46
47
48
49
class DSU{
public:
vector<int> parent;
vector<int> rank;
int count;
DSU(int V){
count = V;
parent.resize(V+1);
rank.resize(V+1);
for(int i=0; i<=V; i++){
rank[i] = 0;
parent[i] = i;
}
}
int Find(int u){
if(u!=parent[u])
parent[u] = Find(parent[u]);
return parent[u];
}
void Union(int u, int v){
u = Find(u);
v = Find(v);
if(u==v)
return;
count -= 1;
if(rank[u]<rank[v])
swap(u,v);
parent[v] = u;
if(rank[u]==rank[v])
rank[u]++;
return;
}
int getcount(){
return count;
}
};
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
DSU ds(n);
for(auto & edge: edges)
ds.Union(edge[0],edge[1]);
return ds.getcount();
}
};