posts: union-find: add presentation
This commit is contained in:
parent
cf59a75dca
commit
c714b14791
|
@ -24,3 +24,27 @@ operations: `ds.union(lhs, rhs)` and `ds.find(elem)`.
|
||||||
[series]: {{< ref "/series/lesser-known-algorithms-and-data-structures/">}}
|
[series]: {{< ref "/series/lesser-known-algorithms-and-data-structures/">}}
|
||||||
|
|
||||||
<!--more-->
|
<!--more-->
|
||||||
|
|
||||||
|
## What does it do?
|
||||||
|
|
||||||
|
The _Union-Find_ data structure allows one to store a collection of sets of
|
||||||
|
elements, with operations for adding new sets, merging two sets into one, and
|
||||||
|
finding the representative member of a set. Not only does it do all that, but it
|
||||||
|
does it in almost constant (amortized) time!
|
||||||
|
|
||||||
|
Here is a small motivating example for using the _Disjoint Set_ data structure:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def connected_components(graph: Graph) -> list[set[Node]]:
|
||||||
|
# Initialize the disjoint set so that each node is in its own set
|
||||||
|
ds: DisjointSet[Node] = DisjointSet(graph.nodes)
|
||||||
|
# Each edge is a connection, merge both sides into the same set
|
||||||
|
for (start, dest) in graph.edges:
|
||||||
|
ds.union(start, dest)
|
||||||
|
# Connected components share the same (arbitrary) root
|
||||||
|
components: dict[Node, set[Node]] = defaultdict(set)
|
||||||
|
for n in graph.nodes:
|
||||||
|
components[ds.find(n)].add(n)
|
||||||
|
# Return a list of disjoint sets corresponding to each connected component
|
||||||
|
return list(components.values())
|
||||||
|
```
|
||||||
|
|
Loading…
Reference in a new issue