Implementation of disjoint set data structure (aka union-find data structure)
Project description
Disjoint Set (Union-Find) Data Structure
This repository contains a Python implementation of the Disjoint Set (also known as Union-Find) data structure. The implementation includes optimizations such as path compression and union by rank to ensure efficient operations.
Features
- Find: Determine the root of the set containing a given element.
- Union: Merge two sets into one.
- Connected: Check if two elements are in the same set.
- Path Compression: Flattens the tree during
findoperations for faster future queries. - Union by Rank: Keeps the tree balanced by attaching smaller trees to larger ones.
Code Overview
DisjointSet Class
Attributes
parent: A list where each element points to its parent in the set.rank: A list representing the rank (approximate depth) of each set.
Methods
__init__(size: int): Initializes the disjoint-set withsizeelements.find(x: int) -> int: Finds the root of the set containingxwith path compression.union(x: int, y: int): Merges the sets containingxandyusing union by rank.connected(x: int, y: int) -> bool: Checks ifxandyare in the same set.
Example Usage
# Create a disjoint-set with 10 elements
ds = DisjointSet(10)
# Perform some union operations
ds.union(1, 2)
ds.union(3, 4)
ds.union(1, 3)
# Check if elements are connected
print(ds.connected(1, 4)) # Output: True
print(ds.connected(1, 5)) # Output: False
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file disjoint_set_struct-0.0.1.tar.gz.
File metadata
- Download URL: disjoint_set_struct-0.0.1.tar.gz
- Upload date:
- Size: 4.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
db398c062b4f7c5c32ccc159da200076a2184ba790cf4a02777e1dea6fccae38
|
|
| MD5 |
25c7a589c136747a832d92d9267c027d
|
|
| BLAKE2b-256 |
6551e81db28e28fc5487fdfc061f20e29e14a089ccc9ccc44b639be70b2d30a4
|
File details
Details for the file disjoint_set_struct-0.0.1-py3-none-any.whl.
File metadata
- Download URL: disjoint_set_struct-0.0.1-py3-none-any.whl
- Upload date:
- Size: 4.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fbcb69d15370a39e15ec82f2ad0341b06e99110e5217fd174653a549a3641d62
|
|
| MD5 |
0208883ab4cfb6a43b98b3733c567556
|
|
| BLAKE2b-256 |
7178db77aeff27d46fc019ce50d28b2966a35f70cd96afb9c84738a0a76102fb
|