The union-find (disjoint set) data structure is a powerful tool for managing a partition of a set into disjoint subsets. It supports two main operations, find and union, allowing you to efficiently determine which subset a particular element is in and to merge two subsets into a single subset. This data structure is commonly used in algorithms such as Kruskal's algorithm for finding minimum spanning trees.
class UnionFind {
private var parent: [Int]
private var rank: [Int]
init(size: Int) {
parent = Array(0.. Int {
if parent[p] != p {
parent[p] = find(parent[p]) // Path compression
}
return parent[p]
}
func union(_ p: Int, _ q: Int) {
let rootP = find(p)
let rootQ = find(q)
if rootP != rootQ {
// Union by rank
if rank[rootP] > rank[rootQ] {
parent[rootQ] = rootP
} else if rank[rootP] < rank[rootQ] {
parent[rootP] = rootQ
} else {
parent[rootQ] = rootP
rank[rootP] += 1
}
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?