data_structures
union_find_union.c
Go to the documentation of this file.
1 /* ************************************************************************** */
3 /* */
4 /* ::: :::::::: */
5 /* union_find_union.c :+: :+: :+: */
6 /* +:+ +:+ +:+ */
7 /* By: unite <marvin@42.fr> +#+ +:+ +#+ */
8 /* +#+#+#+#+#+ +#+ */
9 /* Created: 2020/07/21 22:00:39 by unite #+# #+# */
10 /* Updated: 2020/09/07 22:44:10 by unite ### ########.fr */
11 /* */
12 /* ************************************************************************** */
13 
14 #include "union_find.h"
15 
16 void union_find_union(t_union_find *uf, size_t p, size_t q)
17 {
18  size_t root_p;
19  size_t root_q;
20 
21  if (p >= uf->size || q >= uf->size)
22  ds_exit_set(EINVAL);
23  root_p = union_find_find(uf, p);
24  root_q = union_find_find(uf, q);
25  if (root_p == root_q)
26  return ;
27  if (uf->nchild[root_p] > uf->nchild[root_q])
28  {
29  uf->parent[root_q] = root_p;
30  uf->nchild[root_p] += uf->nchild[q];
31  }
32  else
33  {
34  uf->parent[root_p] = root_q;
35  uf->nchild[root_q] += uf->nchild[p];
36  }
37  uf->count--;
38  return ;
39 }
s_union_find::count
size_t count
The number of disconnected sets.
Definition: union_find.h:41
s_union_find::parent
size_t * parent
An array with each element's parent.
Definition: union_find.h:38
union_find.h
s_union_find
Weighted quick-union by rank with path compression by halving.
Definition: union_find.h:36
union_find_union
void union_find_union(t_union_find *uf, size_t p, size_t q)
Merges the set containing element p with the set containing element q.
Definition: union_find_union.c:16
union_find_find
size_t union_find_find(const t_union_find *uf, size_t p)
Returns the canonical element of the set containing the specified element.
Definition: union_find_find.c:16
s_union_find::nchild
size_t * nchild
An array with the number of each element's children.
Definition: union_find.h:39
ds_exit_set
void ds_exit_set(int err)
Set errno to the specified value, print the error message, and exit the process.
Definition: ds_exit_set.c:22
s_union_find::size
size_t size
The number of elements.
Definition: union_find.h:40