-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdsu.cpp
More file actions
48 lines (44 loc) · 1.16 KB
/
dsu.cpp
File metadata and controls
48 lines (44 loc) · 1.16 KB
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
class dsu {
public :
int n , max_component;
vector<int> P , R , S;
dsu(int n){
this->n = n ;
P.resize(n+1) ;
R.resize(n+1) ;
S.resize(n+1) ;
for(int i=1;i<=n;i++){
R[i] = 0 ;
P[i] = i ;
S[i] = 1 ;
}
max_component = 1 ;
}
int find(int x){
if(x != P[x]){
P[x] = find(P[x]) ;
}
return P[x] ;
}
bool add_edge(int x,int y){
int rx , ry ;
rx = find(x) ;
ry = find(y) ;
if(rx != ry){
if(R[rx] < R[ry]){
P[rx] = ry ;
S[ry] += S[rx] ;
max_component = max(max_component,S[ry]) ;
}else{
P[ry] = rx ;
S[rx] += S[ry] ;
max_component = max(max_component,S[rx]) ;
}
if(R[rx] == R[ry]){
R[rx] ++ ;
}
return true ;
}
return false ;
}
};