2011-05-12 17:24:54 +02:00
|
|
|
import option::none;
|
|
|
|
import option::some;
|
2011-04-07 18:01:21 -07:00
|
|
|
|
|
|
|
// A very naive implementation of union-find with unsigned integer nodes.
|
|
|
|
|
2011-05-12 17:24:54 +02:00
|
|
|
type node = option::t[uint];
|
2011-04-07 18:01:21 -07:00
|
|
|
type ufind = rec(mutable vec[mutable node] nodes);
|
|
|
|
|
|
|
|
fn make() -> ufind {
|
2011-05-16 18:21:22 -07:00
|
|
|
let vec[mutable node] v = [mutable none[uint]];
|
2011-05-12 17:24:54 +02:00
|
|
|
_vec::pop(v); // FIXME: botch
|
2011-04-07 18:01:21 -07:00
|
|
|
ret rec(mutable nodes=v);
|
|
|
|
}
|
|
|
|
|
2011-04-08 14:53:16 -07:00
|
|
|
fn make_set(&ufind ufnd) -> uint {
|
2011-05-12 17:24:54 +02:00
|
|
|
auto idx = _vec::len(ufnd.nodes);
|
2011-05-16 18:21:22 -07:00
|
|
|
ufnd.nodes += [mutable none[uint]];
|
2011-04-08 14:53:16 -07:00
|
|
|
ret idx;
|
2011-04-07 18:01:21 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
fn find(&ufind ufnd, uint n) -> uint {
|
|
|
|
alt (ufnd.nodes.(n)) {
|
2011-04-08 14:53:16 -07:00
|
|
|
case (none[uint]) { ret n; }
|
|
|
|
case (some[uint](?m)) {
|
|
|
|
// TODO: "be"
|
|
|
|
ret find(ufnd, m);
|
|
|
|
}
|
2011-04-07 18:01:21 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn union(&ufind ufnd, uint m, uint n) {
|
|
|
|
auto m_root = find(ufnd, m);
|
|
|
|
auto n_root = find(ufnd, n);
|
|
|
|
auto ptr = some[uint](n_root);
|
2011-04-08 14:53:16 -07:00
|
|
|
ufnd.nodes.(m_root) = ptr;
|
2011-04-07 18:01:21 -07:00
|
|
|
}
|
|
|
|
|