| 520 | |
| 521 | impl<T: Clone + Ord> UnionFind<T> for BTreeMap<T, T> { |
| 522 | fn find<'a>(&'a mut self, x: &T) -> Option<&'a T> { |
| 523 | if !self.contains_key(x) { |
| 524 | None |
| 525 | } else { |
| 526 | if self[x] != self[&self[x]] { |
| 527 | // Path halving |
| 528 | let mut y = self[x].clone(); |
| 529 | while y != self[&y] { |
| 530 | let grandparent = self[&self[&y]].clone(); |
| 531 | *self.get_mut(&y).unwrap() = grandparent; |
| 532 | y.clone_from(&self[&y]); |
| 533 | } |
| 534 | *self.get_mut(x).unwrap() = y; |
| 535 | } |
| 536 | Some(&self[x]) |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | fn union(&mut self, x: &T, y: &T) { |
| 541 | match (self.find(x).is_some(), self.find(y).is_some()) { |