-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdisjoint_set.rs
57 lines (50 loc) · 1.25 KB
/
disjoint_set.rs
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
/// Very simple disjoint set implementation for clustering cropped textures
/// - fixed size
/// - cannot divide the union
pub struct DisjointSet {
parent: Vec<usize>,
}
impl DisjointSet {
pub fn new(num_elements: usize) -> Self {
DisjointSet {
parent: (0..num_elements).collect(),
}
}
#[inline]
pub fn root(&self, x: usize) -> usize {
if self.parent[x] == x {
x
} else {
self.root(self.parent[x])
}
}
#[inline]
pub fn unite(&mut self, x: usize, y: usize) {
let root_x = self.root(x);
let root_y = self.root(y);
self.parent[root_x] = root_y;
}
#[allow(dead_code)]
fn is_same(&self, x: usize, y: usize) -> bool {
self.root(x) == self.root(y)
}
#[inline]
pub fn compress(&mut self) {
self.parent = self.parent.iter().map(|&x| self.root(x)).collect();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_disjoint_set_unite() {
let mut ds = DisjointSet::new(5);
ds.unite(0, 1);
ds.unite(3, 4);
ds.unite(1, 2);
assert!(ds.is_same(0, 2));
assert!(!ds.is_same(0, 3));
ds.unite(0, 3);
assert!(ds.is_same(0, 4));
}
}