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
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use std::cell::Cell;
use std::fmt::{self, Debug};

use super::ElementType;

/// Array-based union-find representing a set of disjoint sets.
#[derive(Clone)]
pub struct UnionFind<Element: ElementType = usize> {
    elements: Vec<Cell<Element>>,
    ranks: Vec<u8>,
}

impl<Element: Debug + ElementType> Debug for UnionFind<Element> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "UnionFind({:?})", self.elements)
    }
}

impl<Element: ElementType> Default for UnionFind<Element> {
    fn default() -> Self {
        UnionFind::new(0)
    }
}

impl<Element: ElementType> UnionFind<Element> {
    /// Creates a new union-find of `size` elements.
    ///
    /// # Panics
    ///
    /// If `size` elements would overflow the element type `Element`.
    pub fn new(size: usize) -> Self {
        UnionFind {
            elements: (0..size).map(|i| {
                let e = Element::from_usize(i).expect("UnionFind::new: overflow");
                Cell::new(e)
            }).collect(),
            ranks: vec![0; size],
        }
    }

    /// The number of elements in all the sets.
    pub fn len(&self) -> usize {
        self.elements.len()
    }

    /// Is the union-find devoid of elements?
    ///
    /// It is possible to create an empty `UnionFind` and then add
    /// elements with [`alloc`](#method.alloc).
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    /// Creates a new element in a singleton set.
    ///
    /// # Panics
    ///
    /// If allocating another element would overflow the element type
    /// `Element`.
    pub fn alloc(&mut self) -> Element {
        let result = Element::from_usize(self.elements.len())
                       .expect("UnionFind::alloc: overflow");
        self.elements.push(Cell::new(result));
        self.ranks.push(0);
        result
    }

    /// Joins the sets of the two given elements.
    ///
    /// Returns whether anything changed. That is, if the sets were
    /// different, it returns `true`, but if they were already the same
    /// then it returns `false`.
    pub fn union(&mut self, a: Element, b: Element) -> bool {
        let a = self.find(a);
        let b = self.find(b);

        if a == b { return false; }

        let rank_a = self.rank(a);
        let rank_b = self.rank(b);

        if rank_a > rank_b {
            self.set_parent(b, a);
        } else if rank_b > rank_a {
            self.set_parent(a, b);
        } else {
            self.set_parent(a, b);
            self.increment_rank(b);
        }

        true
    }

    /// Finds the representative element for the given element’s set.
    pub fn find(&self, mut element: Element) -> Element {
        while element != self.parent(element) {
            self.set_parent(element, self.grandparent(element));
            element = self.parent(element);
        }

        element
    }

    /// Determines whether two elements are in the same set.
    pub fn equiv(&self, a: Element, b: Element) -> bool {
        self.find(a) == self.find(b)
    }

    /// Forces all laziness, so that each element points directly to its
    /// set’s representative.
    pub fn force(&self) {
        for i in 0 .. self.len() {
            self.find(Element::from_usize(i).unwrap());
        }
    }

    /// Returns a vector of set representatives.
    pub fn as_vec(&self) -> Vec<Element> {
        self.force();
        self.elements.iter().map(Cell::get).collect()
    }

    // HELPERS

    fn rank(&self, element: Element) -> u8 {
        self.ranks[element.to_usize()]
    }

    fn increment_rank(&mut self, element: Element) {
        let i = element.to_usize();
        let (rank, over) = self.ranks[i].overflowing_add(1);
        assert!(!over, "UnionFind: rank overflow");
        self.ranks[i] = rank;
    }

    fn parent(&self, element: Element) -> Element {
        self.elements[element.to_usize()].get()
    }

    fn set_parent(&self, element: Element, parent: Element) {
        self.elements[element.to_usize()].set(parent);
    }

    fn grandparent(&self, element: Element) -> Element {
        self.parent(self.parent(element))
    }

}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn len() {
        assert_eq!(5, UnionFind::<u32>::new(5).len());
    }

    #[test]
    fn union() {
        let mut uf = UnionFind::<u32>::new(8);
        assert!(!uf.equiv(0, 1));
        uf.union(0, 1);
        assert!(uf.equiv(0, 1));
    }

    #[test]
    fn unions() {
        let mut uf = UnionFind::<usize>::new(8);
        assert!(uf.union(0, 1));
        assert!(uf.union(1, 2));
        assert!(uf.union(4, 3));
        assert!(uf.union(3, 2));
        assert!(! uf.union(0, 3));

        assert!(uf.equiv(0, 1));
        assert!(uf.equiv(0, 2));
        assert!(uf.equiv(0, 3));
        assert!(uf.equiv(0, 4));
        assert!(!uf.equiv(0, 5));

        uf.union(5, 3);
        assert!(uf.equiv(0, 5));

        uf.union(6, 7);
        assert!(uf.equiv(6, 7));
        assert!(!uf.equiv(5, 7));

        uf.union(0, 7);
        assert!(uf.equiv(5, 7));
    }
}