@@ -2,6 +2,8 @@ import option::none;
2
2
import option:: some;
3
3
4
4
// A very naive implementation of union-find with unsigned integer nodes.
5
+ // Maintains the invariant that the root of a node is always equal to or less
6
+ // than the node itself.
5
7
6
8
type node = option:: t [ uint ] ;
7
9
type ufind = rec ( mutable vec[ mutable node] nodes ) ;
@@ -20,18 +22,27 @@ fn make_set(&ufind ufnd) -> uint {
20
22
21
23
fn find ( & ufind ufnd, uint n) -> uint {
22
24
alt ( ufnd. nodes . ( n) ) {
23
- case ( none[ uint] ) { ret n; }
24
- case ( some[ uint] ( ?m) ) {
25
- // TODO: "be"
26
- ret find ( ufnd, m) ;
27
- }
25
+ case ( none[ uint] ) { ret n; }
26
+ case ( some[ uint] ( ?m) ) { be find ( ufnd, m) ; }
28
27
}
29
28
}
30
29
31
30
fn union ( & ufind ufnd, uint m, uint n) {
32
31
auto m_root = find ( ufnd, m) ;
33
32
auto n_root = find ( ufnd, n) ;
34
- auto ptr = some[ uint] ( n_root) ;
35
- ufnd. nodes . ( m_root) = ptr;
33
+ if ( m_root < n_root) {
34
+ ufnd. nodes . ( n_root) = some[ uint] ( m_root) ;
35
+ } else {
36
+ ufnd. nodes . ( m_root) = some[ uint] ( n_root) ;
37
+ }
38
+ }
39
+
40
+ // Removes all sets with IDs greater than or equal to the given value.
41
+ fn prune ( & ufind ufnd, uint n) {
42
+ // TODO: Use "slice" once we get rid of "mutable?"
43
+ while ( n != 0 u) {
44
+ vec:: pop[ node] ( ufnd. nodes ) ;
45
+ n -= 1 u;
46
+ }
36
47
}
37
48
0 commit comments