repl.it
@pyelias/

disjoint-set

Python

No description

fork
loading
Files
  • main.py
main.py
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
class DisjointSet():
  def __init__(self):
    self.parents = {}
    self.ranks = {}
  
  def find(self, val):
    while True:
      parent = self.parents[val]
      if parent == val:
        return val
      grandparent = self.parents[parent]
      val = self.parents[val] = grandparent
  
  def _rank(self, set_):
    return self.ranks.setdefault(set_, 0)

  def union(self, a, b):
    a, b = self.find(a), self.find(b)
    ar, br = self._rank(a), self._rank(b)
    if ar < br:
      self.parents[a] = b
      del self.ranks[a]
    elif br < ar:
      self.parents[b] = a
      del self.ranks[b]
    else:
      self.parents[a] = b
      del self.ranks[a]
      self.ranks[b] += 1
  
  def add(self, val):
    if val not in self.parents:
      self.parents[val] = val

s = DisjointSet()
s.add(1)
s.add(2)
s.add(3)
s.union(1, 2)
s.union(1, 3)
print(s.find(2))
Fetching token
?