-
Notifications
You must be signed in to change notification settings - Fork 5
/
tc_disjoint.c
executable file
·114 lines (98 loc) · 2.36 KB
/
tc_disjoint.c
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* \file disjoint.c
*
* \author David Ray Thompson\n
*
* Copyright 2012, by the California Institute of Technology. ALL RIGHTS
* RESERVED. United States Government Sponsorship acknowledged. Any
* commercial use must be negotiated with the Office of Technology
* Transfer at the California Institute of Technology.
*/
#include <stdlib.h>
#include <string.h>
#include "tc_disjoint.h"
#ifndef TC_DISJOINT_C
#define TC_DISJOINT_C
/* Initialize the merge union structure to entirely disjoint sets */
int tc_init_disjoint(tc_disjoint **d, int nlabels)
{
int i;
if (d==NULL || nlabels < 1)
{
tc_write_log("Bad parameters to merge union initialization!\n");
return ERR;
}
tc_disjoint *dnew = (tc_disjoint *) malloc(sizeof(tc_disjoint));
if (dnew == NULL)
{
tc_write_log("Cannot initialize merge unions structure!\n");
return ERR;
}
dnew->nlabels = nlabels;
dnew->parent = (int *) malloc(sizeof(int) * nlabels);
if (dnew->parent == NULL)
{
tc_write_log("Cannot initialize merge union parents!\n");
free(dnew);
return ERR;
}
dnew->rank = (int *) malloc(sizeof(int) * nlabels);
if (dnew->rank == NULL)
{
tc_write_log("Cannot initialize merge union ranks\n");
free(dnew->parent);
free(dnew);
return ERR;
}
for (i=0; i<nlabels; i++)
{
dnew->parent[i] = i;
dnew->rank[i] = 1;
}
*d = dnew;
return OK;
}
/* Freeeeeedom!!! */
void tc_free_disjoint(tc_disjoint *d)
{
if (d==NULL)
{
tc_write_log("Cannot free a null pointer!\n");
return;
}
free(d->parent);
free(d->rank);
free(d);
}
/* Find the equivalence class for a given point */
int tc_find_disjoint(tc_disjoint *d, int i)
{
while (d->parent[i] != i)
{
i = d->parent[i];
}
return i;
}
/* Merge two equivalence classes into a (hopefully somewhat balanced) tree */
void tc_merge_disjoint(tc_disjoint *d, int i, int j)
{
int ic = tc_find_disjoint(d,i);
int jc = tc_find_disjoint(d,j);
if (d->rank[ic] > d->rank[jc])
{
d->parent[jc] = ic;
if (d->rank[ic] == d->rank[jc])
{
d->rank[ic]++;
}
}
else
{
d->parent[ic] = jc;
if (d->rank[ic] == d->rank[jc])
{
d->rank[jc]++;
}
}
}
#endif