Struct UnionFind

Source
pub struct UnionFind<K> { /* private fields */ }
Expand description

UnionFind<K> is a disjoint-set data structure. It tracks set membership of n elements indexed from 0 to n - 1. The scalar type is K which must be an unsigned integer type.

http://en.wikipedia.org/wiki/Disjoint-set_data_structure

Too awesome not to quote:

“The amortized time per operation is O(α(n)) where α(n) is the inverse of f(x) = A(x, x) with A being the extremely fast-growing Ackermann function.”

Implementations§

Source§

impl<K> UnionFind<K>
where K: IndexType,

Source

pub fn new(n: usize) -> Self

Create a new UnionFind of n disjoint sets.

Source

pub const fn new_empty() -> Self

Create a new UnionFind with no elements.

Source

pub fn len(&self) -> usize

Returns the number of elements in the union-find data-structure.

Source

pub fn is_empty(&self) -> bool

Returns true if there are no elements in the union-find data-structure.

Source

pub fn new_set(&mut self) -> K

Adds a new disjoint set and returns the index of the new set.

The new disjoint set is always added to the end, so the returned index is the same as the number of elements before calling this function.

Time Complexity Takes amortized O(1) time.

Source

pub fn find(&self, x: K) -> K

Return the representative for x.

Panics if x is out of bounds.

Source

pub fn try_find(&self, x: K) -> Option<K>

Return the representative for x or None if x is out of bounds.

Source

pub fn find_mut(&mut self, x: K) -> K

Return the representative for x.

Write back the found representative, flattening the internal datastructure in the process and quicken future lookups.

Panics if x is out of bounds.

Source

pub fn try_find_mut(&mut self, x: K) -> Option<K>

Return the representative for x or None if x is out of bounds.

Write back the found representative, flattening the internal datastructure in the process and quicken future lookups.

Source

pub fn equiv(&self, x: K, y: K) -> bool

Returns true if the given elements belong to the same set, and returns false otherwise.

Panics if x or y is out of bounds.

Source

pub fn try_equiv(&self, x: K, y: K) -> Result<bool, K>

Returns Ok(true) if the given elements belong to the same set, and returns Ok(false) otherwise.

If x or y are out of bounds, it returns Err with the first bad index found.

Source

pub fn union(&mut self, x: K, y: K) -> bool

Unify the two sets containing x and y.

Return false if the sets were already the same, true if they were unified.

Panics if x or y is out of bounds.

Source

pub fn try_union(&mut self, x: K, y: K) -> Result<bool, K>

Unify the two sets containing x and y.

Return Ok(false) if the sets were already the same, Ok(true) if they were unified.

If x or y are out of bounds, it returns Err with first found bad index. But if x == y, the result will be Ok(false) even if the indexes go out of bounds.

Source

pub fn into_labeling(self) -> Vec<K>

Return a vector mapping each element to its representative.

Source§

impl<K> UnionFind<K>

Source

pub fn with_capacity(capacity: usize) -> Self

Constructs a new, empty UnionFind<K> with at least the specified capacity.

This acts similarly to Vec::with_capacity.

Source

pub fn capacity(&self) -> usize

Returns the total number of elements the UnionFind can hold without reallocating.

§Examples
use petgraph::unionfind::UnionFind;

let mut uf: UnionFind<u32> = UnionFind::with_capacity(10);
uf.new_set();
assert!(uf.capacity() >= 10);
Source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional more elements to be inserted in the given UnionFind<K>. The collection may reserve more space to speculatively avoid frequent reallocations. After calling reserve, capacity will be greater than or equal to self.len() + additional. Does nothing if capacity is already sufficient.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples
use petgraph::unionfind::UnionFind;

let mut uf: UnionFind<u32> = UnionFind::new(3);
uf.reserve(10);
assert!(uf.capacity() >= 13);
Source

pub fn reserve_exact(&mut self, additional: usize)

Reserves the minimum capacity for at least additional more elements to be inserted in the given UnionFind<K>. Unlike reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling reserve_exact, capacity will be greater than or equal to self.len() + additional. Does nothing if the capacity is already sufficient.

Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer reserve if future insertions are expected.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples
use petgraph::unionfind::UnionFind;

let mut uf: UnionFind<u32> =  UnionFind::new_empty();
uf.reserve_exact(10);
assert!(uf.capacity() >= 10);
Source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve capacity for at least additional more elements to be inserted in the given UnionFind<K>. The collection may reserve more space to speculatively avoid frequent reallocations. After calling try_reserve, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs.

§Errors

If the capacity overflows, or the allocator reports a failure, then an error is returned.

Source

pub fn try_reserve_exact( &mut self, additional: usize, ) -> Result<(), TryReserveError>

Tries to reserve the minimum capacity for at least additional elements to be inserted in the given UnionFind<K>. Unlike try_reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling try_reserve_exact, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). Does nothing if the capacity is already sufficient.

Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer try_reserve if future insertions are expected.

§Errors

If the capacity overflows, or the allocator reports a failure, then an error is returned.

Source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of the UnionFind as much as possible.

The behavior of this method depends on the allocator, which may either shrink the collection in-place or reallocate. The resulting UnionFind might still have some excess capacity, just as is the case for with_capacity. See Vec::shrink_to_fit for more details, since the implementation is based on this method.

§Examples
use petgraph::unionfind::UnionFind;

let mut uf: UnionFind<u32> = UnionFind::with_capacity(10);

for _ in 0..3 {
    uf.new_set();
}

assert!(uf.capacity() >= 10);
uf.shrink_to_fit();
assert!(uf.capacity() >= 3);
Source

pub fn shrink_to(&mut self, min_capacity: usize)

Shrinks the capacity of the UnionFind with a lower bound.

The capacity will remain at least as large as both the length and the supplied value.

If the current capacity is less than the lower limit, this is a no-op.

§Examples
use petgraph::unionfind::UnionFind;

let mut uf: UnionFind<u32> = UnionFind::with_capacity(10);

for _ in 0..3 {
    uf.new_set();
}

assert!(uf.capacity() >= 10);
uf.shrink_to(4);
assert!(uf.capacity() >= 4);
uf.shrink_to(0);
assert!(uf.capacity() >= 3);

Trait Implementations§

Source§

impl<K: Clone> Clone for UnionFind<K>

Source§

fn clone(&self) -> UnionFind<K>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K: Debug> Debug for UnionFind<K>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<K> Default for UnionFind<K>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<K> Freeze for UnionFind<K>

§

impl<K> RefUnwindSafe for UnionFind<K>
where K: RefUnwindSafe,

§

impl<K> Send for UnionFind<K>
where K: Send,

§

impl<K> Sync for UnionFind<K>
where K: Sync,

§

impl<K> Unpin for UnionFind<K>
where K: Unpin,

§

impl<K> UnwindSafe for UnionFind<K>
where K: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.