-
Notifications
You must be signed in to change notification settings - Fork 524
Expand file tree
/
Copy pathdisjoint_sets.rs
More file actions
38 lines (33 loc) · 767 Bytes
/
disjoint_sets.rs
File metadata and controls
38 lines (33 loc) · 767 Bytes
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
struct DisjointSets {
p: Vec<usize>,
}
impl DisjointSets {
pub fn new(n: usize) -> Self {
DisjointSets {
p: (0..n).collect(),
}
}
pub fn root(&mut self, x: usize) -> usize {
if x != self.p[x] {
self.p[x] = self.root(self.p[x]);
}
self.p[x]
}
pub fn unite(&mut self, a: usize, b: usize) {
let a = self.root(a);
let b = self.root(b);
self.p[b] = a;
}
}
#[cfg(test)]
mod tests {
use crate::structures::disjoint_sets::DisjointSets;
#[test]
fn basic_test() {
let mut ds = DisjointSets::new(3);
ds.unite(0, 2);
assert_eq!(ds.root(0), 0);
assert_eq!(ds.root(1), 1);
assert_eq!(ds.root(2), 0);
}
}