-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuf.c
79 lines (73 loc) · 1.62 KB
/
uf.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
#include <stdio.h>
#include <stdlib.h>
#include "uf.h"
UFelem *
UFalloc ( int n )
{
UFelem *uf;
uf = ( UFelem * ) malloc ( n * sizeof ( UFelem ) );
if ( uf == ( UFelem * ) NULL )
fprintf ( stderr, "ERROR: uf NULL\n" );
return ( uf );
}
void
UFfree ( UFelem * uf )
{
free ( uf );
return;
}
void
UFcreate ( UFelem * uf, int n )
{
int i;
for ( i = 0; i < n; i++ )
{
uf[i].rank = 0;
uf[i].parent = i; /* roots point to themselves */
}
return;
}
int
UFunion ( UFelem * uf, int i, int j )
{
/* union by rank; assumes that i, j are roots */
int root;
if ( uf[i].rank >= uf[j].rank )
{
uf[j].parent = i;
if ( uf[i].rank == uf[j].rank )
uf[i].rank++;
if ( uf[i].handleE < uf[j].handleE )
{
uf[i].handleB = uf[j].handleB;
uf[i].handleE = uf[j].handleE;
}
root = i;
}
else
{
/* uf[i].rank < uf[j].rank */
uf[i].parent = j;
if ( uf[j].handleE < uf[i].handleE )
{
uf[j].handleB = uf[i].handleB;
uf[j].handleE = uf[i].handleE;
}
root = j;
}
return ( root );
}
int
UFfind ( UFelem * uf, int i )
{
/* uses halving rather than full compression ; thus only one pass */
int above;
above = uf[i].parent;
while ( above != uf[above].parent )
{ /* parent is not the root */
uf[i].parent = uf[above].parent; /* point to my grandparent */
i = uf[above].parent; /* move up two levels */
above = uf[i].parent;
}
return ( above );
}