github.com/whtcorpsinc/MilevaDB-Prod@v0.0.0-20211104133533-f57f4be3b597/soliton/disjointset/int_set.go (about) 1 // Copyright 2020 WHTCORPS INC, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package disjointset 15 16 // IntSet is the int disjoint set. 17 type IntSet struct { 18 parent []int 19 } 20 21 // NewIntSet returns a new int disjoint set. 22 func NewIntSet(size int) *IntSet { 23 p := make([]int, size) 24 for i := range p { 25 p[i] = i 26 } 27 return &IntSet{parent: p} 28 } 29 30 // Union unions two sets in int disjoint set. 31 func (m *IntSet) Union(a int, b int) { 32 m.parent[m.FindRoot(a)] = m.FindRoot(b) 33 } 34 35 // FindRoot finds the representative element of the set that `a` belongs to. 36 func (m *IntSet) FindRoot(a int) int { 37 if a == m.parent[a] { 38 return a 39 } 40 m.parent[a] = m.FindRoot(m.parent[a]) 41 return m.parent[a] 42 }