-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion_find.c
More file actions
61 lines (53 loc) · 1.21 KB
/
union_find.c
File metadata and controls
61 lines (53 loc) · 1.21 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
49
50
51
52
53
54
55
56
57
58
59
60
61
// union-find implementation with path compression
#include <stdio.h>
#include <stdbool.h>
int find(int x , int Array[]) // returns the parent node of element x
{
int root = x;
while(root != Array[root])
root = Array[root];
// root = Array[root] , that means root is parent root for x
// doing path compression
while(x != root)
{
int temp = Array[x];
Array[x] = root;
x = temp;
}
return root;
}
bool is_cycle(int p , int q , int Array[]) // returns true if they will make a cycle
{
return find(p , Array) == find(q , Array);
}
void unify(int p ,int q , int Array[] , int size[])
{
int root1 = find(p);
int root2 = find(q);
if(root1 == root2)
return;
int size1 = size[root1];
int size2 = size[root2];
if(size1 >= size2)
{
size[root1] += size[root2];
Array[root2] = root1;
}
else
{
size[root2] += size[root1];
Array[root1] = root2;
}
}
int main()
{
int n;
scanf("%d", &n);
int Array[n + 1];
int size[n + 1]; // stores the size of each set
for (int i = 1; i <= n; i++)
{
Array[i] = i; // if Array[i] = i , then i is parent node
size[i] = 1;
}
}