forked from shim1998/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
union_find.cpp
51 lines (46 loc) · 1.09 KB
/
union_find.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
//I'll be solving https://leetcode.com/submissions/detail/549347434/ to illustrate union find but also tracking the answer
int parent[500]={};
int maxDepth[500]={};
function<int(int)> findParent=[](int u){
if(parent[u]==0){
return u;
}
return parent[u]=findParent(parent[u]);
};
auto unionn=[](int u, int v, int& num){
u=findParent(u);
v=findParent(v);
cout<<u<<" "<<v<<endl;
if(u==v){
return ;
}
num--;
// cout << u<<" : "<<size[u]<<" "<<v<<" : "<<size[v] << endl ;
if(maxDepth[v]>maxDepth[u]){
parent[u]=v;
}
else if(maxDepth[v]<maxDepth[u]){
parent[v]=u;
}
else{
parent[u]=v;
maxDepth[v]++;
}
// cout << u<<" : "<<size[u]<<" "<<v<<" : "<<size[v] << endl<<endl ;
};
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
memset(parent,0,500);
memset(maxDepth,0,500);
int num=isConnected.size();
int ans=num;
for(int i=0;i<num;i++){
for(int j=i+1;j<num;j++){
if(isConnected[i][j])
unionn(i,j,ans);
}
}
return ans;
}
};