-
Notifications
You must be signed in to change notification settings - Fork 0
/
Disjoint Set(Union Find).cpp
59 lines (52 loc) · 1.09 KB
/
Disjoint Set(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
52
53
54
55
56
57
58
59
#include<bits/stdc++.h>
using namespace std;
#define MAX 10000
int root[MAX],weight[MAX];
void make_set(int n){
root[n]=n;
weight[n]=0;
}
int find_root(int n){
if(n!=root[n])
root[n]=find_root(root[n]);
return root[n];
}
void union_set(int x, int y){
int px = find_root(x);
int py = find_root(y);
if(px==py)
return;
if(weight[px]>weight[py]){
root[py]=px;
weight[px]+=weight[py];
} else{
root[px]=py;
weight[py]+=weight[px];
}
}
void disjoint_set(int n){
for(int i=1;i<=n;i++){
make_set(i);
}
}
int main(){
int n,m;
cin>>n>>m;
disjoint_set(n);
for(int i=1;i<=m;i++){
int a,b;
cin>>a>>b;
union_set(a,b);
}
vector< int > st[n+5];
set< int > par;
for(int i=1;i<=n;i++){
st[root[i]].push_back(i);
par.insert(root[i]);
}
for(auto it = par.begin();it!=par.end();it++){
for(int i=0;i<st[*it].size();i++)
cout<<st[*it][i]<<" ";
cout<<endl;
}
}