-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvgen_disjointset.h
84 lines (77 loc) · 2.16 KB
/
vgen_disjointset.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// .___
// ___ __ ____ ___ ___ ____ __| _/
// \ \/ // __ \\ \/ // __ \ / __ |
// \ /\ ___/ > <\ ___// /_/ |
// \_/ \___ >__/\_ \\___ >____ |
// \/ \/ \/ \/ __ .__
// ____ ____ ____ ________________ _/ |_|__| ____ ____
// / ___\_/ __ \ / \_/ __ \_ __ \__ \\ __\ |/ _ \ / \
// / /_/ > ___/| | \ ___/| | \// __ \| | | ( <_> ) | \
// \___ / \___ >___| /\___ >__| (____ /__| |__|\____/|___| /
// /_____/ \/ \/ \/ \/ \/
//
// (c) 2016 - 2020 Karsten Schmidt // ASL 2.0 licensed
#ifndef __vgen_unionfind_h__
#define __vgen_unionfind_h__
struct vgDisjointSet {
int roots[];
int ranks[];
int count;
void init(int n) {
roots = array();
ranks = array();
resize(roots, n);
resize(ranks, n);
count = n;
for (int i = 0; i < n; i++) {
roots[i] = i;
}
}
/**
* Returns canonical ID (tree root) for given `id`. Unless `id`
* already is unified with some other ID, this will always return
* `id` itself (since each node is initially its own root).
*
* @param id
*/
int find(int id) {
int i = id;
while (i != roots[i]) {
i = roots[i] = roots[roots[i]];
}
return i;
}
/**
* Connects combines the trees of the given two node IDs and returns
* the new resulting canonical tree root ID.
*
* @param a
* @param b
*/
int union(int a, b) {
int rootA = this->find(a);
int rootB = this->find(b);
if (rootA == rootB) {
return rootA;
}
count--;
int ra = ranks[rootA];
int rb = ranks[rootB];
if (ra < rb) {
return roots[rootA] = rootB;
}
ra == rb&& ranks[rootA]++;
return roots[rootB] = rootA;
}
/**
* Returns true, if the given two nodes belong to the same tree /
* subset.
*
* @param a
* @param b
*/
int unified(int a, b) {
return this->find(a) == this->find(b);
}
}
#endif