-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathIntDisjointSet.jl
More file actions
56 lines (50 loc) · 1.6 KB
/
IntDisjointSet.jl
File metadata and controls
56 lines (50 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Copyright (c) 2017: Miles Lubin and contributors
# Copyright (c) 2017: Google Inc.
# Copyright (c) 2024: Guillaume Dalle and Alexis Montoison
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
# The code in this file was taken from
# https://github.com/gdalle/SparseMatrixColorings.jl/blob/main/src/Forest.jl
#
# It was copied at the suggestion of Alexis in his JuMP-dev 2025 talk.
#
# @odow made minor changes to match MOI coding styles.
#
# x-ref https://github.com/gdalle/SparseMatrixColorings.jl/pull/190
mutable struct _IntDisjointSet
# current number of distinct trees in the S
number_of_trees::Int
# vector storing the index of a parent in the tree for each edge, used in
# union-find operations
parents::Vector{Int}
# vector approximating the depth of each tree to optimize path compression
ranks::Vector{Int}
_IntDisjointSet(n::Integer) = new(n, collect(1:n), zeros(Int, n))
end
function _find_root!(S::_IntDisjointSet, x::Integer)
p = S.parents[x]
if S.parents[p] != p
S.parents[x] = p = _find_root!(S, p)
end
return p
end
function _root_union!(S::_IntDisjointSet, x::Int, y::Int)
rank1, rank2 = S.ranks[x], S.ranks[y]
if rank1 < rank2
x, y = y, x
elseif rank1 == rank2
S.ranks[x] += 1
end
S.parents[y] = x
S.number_of_trees -= 1
return
end
function _union!(S, x::Int, y::Int)
root_x = _find_root!(S, x)
root_y = _find_root!(S, y)
if root_x != root_y
_root_union!(S, root_x, root_y)
end
return
end