forked from clementfarabet/lua---imgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.h
63 lines (55 loc) · 1.29 KB
/
set.h
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
#ifndef _SET_
#define _SET_
/*
This file provides a very simple data structure to represent
a disjoint set. This code is heavily inspired by Pedro
Felzenszwalb's min-spanning tree code, released under a
GNU GPL license (Copyright (C) 2006 Pedro).
*/
typedef struct {
int pseudorank;
int parent;
int surface;
int id;
} Elt;
typedef struct {
Elt *elts;
int nelts;
} Set;
Set * set_new(int nelts) {
Set *set = (Set *)calloc(1, sizeof(Set));
set->elts = (Elt *)calloc(nelts, sizeof(Elt));
set->nelts = nelts;
int i;
for (i = 0; i < nelts; i++) {
set->elts[i].pseudorank = 0;
set->elts[i].surface = 1;
set->elts[i].parent = i;
set->elts[i].id = -1;
}
return set;
}
void set_free(Set *set) {
free(set->elts);
free(set);
}
int set_find(Set *set, int x) {
int y = x;
while (y != set->elts[y].parent)
y = set->elts[y].parent;
set->elts[x].parent = y;
return y;
}
void set_join(Set *set, int x, int y) {
if (set->elts[x].pseudorank > set->elts[y].pseudorank) {
set->elts[y].parent = x;
set->elts[x].surface += set->elts[y].surface;
} else {
set->elts[x].parent = y;
set->elts[y].surface += set->elts[x].surface;
if (set->elts[x].pseudorank == set->elts[y].pseudorank)
set->elts[y].pseudorank++;
}
set->nelts--;
}
#endif