Skip to content

Commit c0a8115

Browse files
authored
union find (rust)
1 parent 0c35db6 commit c0a8115

File tree

1 file changed

+77
-1
lines changed

1 file changed

+77
-1
lines changed

docs/source/union_find.rst

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,84 @@ It provides operations to add new sets, merge existing sets, and find the set to
66

77
Rust Implementation
88
-------------------
9-
.. source:: union_find/union_find.rs
9+
.. code-block:: rust
10+
11+
struct UnionFind<F>
12+
where F: Fn(usize, usize) -> usize
13+
{
14+
root: Vec<usize>,
15+
size: Vec<usize>,
16+
components: usize,
17+
character: Vec<usize>,
18+
op: F,
19+
}
20+
21+
impl<F> UnionFind<F>
22+
where F: Fn(usize, usize) -> usize
23+
{
24+
pub fn new(n: usize, op: F, init: usize) -> Self {
25+
Self {
26+
root: (0..=n).collect(),
27+
size: vec![1; n + 1],
28+
components: n,
29+
character: vec![init; n + 1],
30+
op,
31+
}
32+
}
33+
34+
pub fn find(&mut self, x: usize) -> usize {
35+
if self.root[x] == x { return x }
36+
self.root[x] = self.find(self.root[x]);
37+
self.root[x]
38+
}
39+
40+
pub fn union(&mut self, x: usize, y: usize, w: usize) -> bool {
41+
let root_x = self.find(x);
42+
let root_y = self.find(y);
1043
44+
if root_x == root_y {
45+
self.character[root_x] = (self.op)(self.character[root_x], w);
46+
return false;
47+
}
48+
49+
if self.size[root_x] > self.size[root_y] {
50+
self.size[root_x] += self.size[root_y];
51+
self.character[root_x] = (self.op)((self.op)(self.character[root_x], self.character[root_y]), w);
52+
self.root[root_y] = root_x;
53+
} else {
54+
self.size[root_y] += self.size[root_x];
55+
self.character[root_y] = (self.op)((self.op)(self.character[root_x], self.character[root_y]), w);
56+
self.root[root_x] = root_y;
57+
}
58+
self.components -= 1;
59+
true
60+
}
61+
62+
pub fn are_connected(&mut self, x: usize, y: usize) -> bool {
63+
self.find(x) == self.find(y)
64+
}
65+
66+
pub fn get_components(&self) -> usize {
67+
self.components
68+
}
69+
70+
pub fn get_root(&mut self, x: usize) -> usize {
71+
self.find(x)
72+
}
73+
74+
pub fn get_character(&mut self, x: usize) -> usize {
75+
let root_x = self.find(x);
76+
self.character[root_x]
77+
}
78+
79+
pub fn get_size(&mut self, x: usize) -> usize {
80+
let root_x = self.find(x);
81+
self.size[root_x]
82+
}
83+
}
84+
85+
86+
1187
Python Implementation
1288
---------------------
1389
.. automodule:: union_find.union_find

0 commit comments

Comments
 (0)