mid_tools/union_find/
mod.rs1use std::{cmp::Ordering, fmt, hash, marker::PhantomData};
4
5use vec_forest::VecForestSet;
6
7pub mod disjoint_set;
8pub mod linked_arc;
9pub mod vec_forest;
10
11#[repr(transparent)]
12pub struct ClassId<C: ?Sized = ()>(usize, PhantomData<fn(&C)>);
13
14impl<C: ?Sized> ClassId<C> {
15 const fn new(id: usize) -> Self { Self(id, PhantomData) }
16
17 #[must_use]
18 pub fn id(self) -> usize { self.0 }
19}
20
21impl<C: ?Sized> fmt::Debug for ClassId<C> {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 let Self(id, PhantomData) = self;
24 f.debug_tuple("EClass").field(id).finish()
25 }
26}
27
28impl<C: ?Sized> Clone for ClassId<C> {
29 fn clone(&self) -> Self { *self }
30}
31
32impl<C: ?Sized> Copy for ClassId<C> {}
33
34impl<C: ?Sized> PartialEq for ClassId<C> {
35 fn eq(&self, other: &Self) -> bool {
36 let Self(id, PhantomData) = *self;
37 id == other.0
38 }
39}
40
41impl<C: ?Sized> Eq for ClassId<C> {}
42
43impl<C: ?Sized> Ord for ClassId<C> {
44 fn cmp(&self, other: &Self) -> Ordering {
45 let Self(id, PhantomData) = *self;
46 id.cmp(&other.0)
47 }
48}
49
50impl<C: ?Sized> PartialOrd for ClassId<C> {
51 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
52}
53
54impl<C: ?Sized> hash::Hash for ClassId<C> {
55 fn hash<H: hash::Hasher>(&self, state: &mut H) {
56 self.0.hash(state);
57 self.1.hash(state);
58 }
59}
60
61impl<C: ?Sized> From<ClassId<C>> for usize {
62 fn from(value: ClassId<C>) -> Self {
63 let ClassId(i, PhantomData) = value;
64 i
65 }
66}
67
68pub type NoNode = disjoint_set::NoNode<usize>;
69pub type Unioned<C> = disjoint_set::Unioned<ClassId<C>>;
70
71pub struct UnionFind<C: ?Sized = ()>(vec_forest::VecForestSet, PhantomData<[ClassId<C>]>);
73
74impl<C: ?Sized> fmt::Debug for UnionFind<C> {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 let Self(nodes, PhantomData) = self;
77 fmt::Debug::fmt(nodes, f)
78 }
79}
80
81impl<C: ?Sized> Default for UnionFind<C> {
82 fn default() -> Self { Self(VecForestSet::default(), PhantomData) }
83}
84
85impl<C: ?Sized> Clone for UnionFind<C> {
86 fn clone(&self) -> Self { Self(self.0.clone(), PhantomData) }
87}
88
89impl<C: ?Sized> UnionFind<C> {
90 #[must_use]
92 #[inline]
93 pub fn new() -> Self { Self::default() }
94
95 #[must_use]
97 #[inline]
98 pub fn len(&self) -> usize { self.0.len() }
99
100 #[must_use]
102 #[inline]
103 pub fn is_empty(&self) -> bool { self.0.is_empty() }
104
105 pub fn classes(&self) -> Classes<C> { Classes(0..self.0.len(), PhantomData) }
106
107 #[inline]
108 pub fn roots(&self) -> Roots<'_, C> { Roots(self.0.roots(), PhantomData) }
109
110 #[inline]
112 pub fn add(&mut self) -> ClassId<C> { ClassId::new(self.0.add()) }
113
114 #[inline]
115 pub fn parent(&self, key: ClassId<C>) -> Result<ClassId<C>, NoNode> {
116 self.0.parent(key.0).map(ClassId::new)
117 }
118
119 #[inline]
126 pub fn find(&self, key: ClassId<C>) -> Result<ClassId<C>, NoNode> {
127 disjoint_set::forest_find(&self.0, key.0).map(ClassId::new)
128 }
129
130 #[inline]
137 pub fn union(&mut self, a: ClassId<C>, b: ClassId<C>) -> Result<Unioned<C>, NoNode> {
138 disjoint_set::ranked_union(&mut self.0, a.0, b.0).map(|u| u.map(ClassId::new))
139 }
140}
141
142#[must_use]
143#[repr(transparent)]
144pub struct Classes<C: ?Sized>(std::ops::Range<usize>, PhantomData<[ClassId<C>]>);
145
146impl<C: ?Sized> fmt::Debug for Classes<C> {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 let Self(it, PhantomData) = self;
149 f.debug_tuple("Classes").field(it).finish()
150 }
151}
152
153impl<C: ?Sized> Iterator for Classes<C> {
154 type Item = ClassId<C>;
155
156 #[inline]
157 fn next(&mut self) -> Option<Self::Item> { self.0.next().map(ClassId::new) }
158}
159
160#[must_use]
161#[repr(transparent)]
162pub struct Roots<'a, C: ?Sized>(vec_forest::Roots<'a>, PhantomData<&'a [ClassId<C>]>);
163
164impl<C: ?Sized> fmt::Debug for Roots<'_, C> {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 let Self(it, PhantomData) = self;
167 fmt::Debug::fmt(it, f)
168 }
169}
170
171impl<C: ?Sized> Clone for Roots<'_, C> {
172 fn clone(&self) -> Self { Self(self.0.clone(), PhantomData) }
173}
174
175impl<C: ?Sized> Iterator for Roots<'_, C> {
176 type Item = ClassId<C>;
177
178 #[inline]
179 fn next(&mut self) -> Option<Self::Item> { self.0.next().map(ClassId::new) }
180}
181
182#[cfg(test)]
183mod test {
184 use prop::sample::SizeRange;
185 use proptest::prelude::*;
186
187 use super::{disjoint_set, linked_arc};
188 use crate::free::Free;
189
190 type Node = linked_arc::LinkedNode<Linked>;
191 #[derive(Debug)]
192 struct Linked(Node);
193
194 impl linked_arc::AsNode for Linked {
195 type Extra = linked_arc::CircularList<Linked>;
196 type Rank = usize;
197
198 #[inline]
199 fn as_node(&self) -> &Node { &self.0 }
200 }
201
202 fn run_diff(len: usize, merges: &[(usize, usize)]) {
203 let mut linked_ids = Free::default();
204 let mut linked = vec![];
205 let mut vec = super::UnionFind::<()>::new();
206
207 for _ in 0..len {
208 linked.push(Node::new_fresh(&mut linked_ids, Linked));
209 assert_eq!(vec.add().id(), *linked.last().unwrap().0.root().id());
210 }
211
212 for (a, b) in merges.iter().copied() {
213 let vec_u = vec
214 .union(super::ClassId::new(a), super::ClassId::new(b))
215 .unwrap();
216
217 let link_u =
218 disjoint_set::ranked_union(&mut linked_arc::LinkedArc, &linked[a], &linked[b])
219 .unwrap();
220
221 assert_eq!(vec_u.map(super::ClassId::id), link_u.map(|n| *n.id()));
222 }
223
224 for (i, linked) in linked.into_iter().enumerate() {
225 assert_eq!(
226 vec.clone().find(super::ClassId::new(i)).unwrap().id(),
227 *linked.0.root().id(),
228 );
229 }
230 }
231
232 fn len_and_merges(
233 len: impl Strategy<Value = usize>,
234 merge_len: impl Clone + Into<SizeRange>,
235 ) -> impl Strategy<Value = (usize, Vec<(usize, usize)>)> {
236 len.prop_flat_map(move |l| {
237 prop::collection::vec((0..l, 0..l), merge_len.clone()).prop_map(move |v| (l, v))
238 })
239 }
240
241 proptest! {
242 #[test]
248 fn differential((len, merges) in len_and_merges(64..=2048_usize, 1..=128)) {
249 run_diff(len, &merges);
250 }
251 }
252}