-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDisJointSetUnion.cpp
61 lines (50 loc) · 1.33 KB
/
DisJointSetUnion.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
#include<iostream>
using namespace std;
#define size 10000
int parent[size];
void makeset(int u){
parent[u]=u;
return;
}
void int_disjoint_set(int NthNodes){
for(int i=1;i<NthNodes;i++){
makeset(i);
}
return;
}
int FindRepresentative(int u){
if(parent[u]==u)
return u;
return parent[u]=FindRepresentative(parent[u]);//with path compression
//return FindRepresentative(parent[u]); //without path compression
}
void Union(int a,int b){
int u=FindRepresentative(a);
int v=FindRepresentative(b);
if(u!=v)
parent[u]=v;
return;
}
int main()
{
int_disjoint_set(6);//There are six nodes.
Union(2,1); // 1
Union(3,2); // /
// 2
// /
// 3
Union(5,4); // 4
Union(6,5); // /
// 5
// /
// 6
Union(4,1); // 1
// / \
// 2 4
// / \
// 3 5
// \
// 6
cout<<FindRepresentative(5)<<endl;
return 0;
}