Skip to content

Commit

Permalink
add union find
Browse files Browse the repository at this point in the history
  • Loading branch information
shellfly committed Dec 18, 2017
1 parent b7dc0cd commit 6c55d9e
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
10 changes: 10 additions & 0 deletions algs4/stopwatch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import time


class StopWatch:

def __init__(self):
self.start = time.time()

def elapsed_time(self):
return round(time.time - self.start, 2)
72 changes: 72 additions & 0 deletions algs4/uf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
class UF:

def __init__(self, n):
self.count = n
self.id = list(range(n))
self.sz = [1] * n

def connected(self, p, q):
return self.find(p) == self.find(q)

# quick-find
# def find(self, p):
# return self.id[p]

# def union(self, p, q):
# pId = self.find(p)
# qId = self.find(q)
# if pId == qId:
# return
# for index, i in enumerate(self.id):
# if i == pId:
# self.id[index] = qId
# self.count -= 1

# quick-union
# def find(self, p):
# while self.id[p] != p:
# p = self.id[p]
# return p

# def union(self, p, q):
# pId = self.find(p)
# qId = self.find(q)
# if pId == qId:
# return
# self.id[pId] = qId
# self.count -= 1

# weighted quick-union
def find(self, p):
while self.id[p] != p:
self.id[p] = self.id[self.id[p]] # path compression
p = self.id[p]
return p

def union(self, p, q):
pId = self.find(p)
qId = self.find(q)
if pId == qId:
return
if self.sz[pId] < self.sz[qId]:
self.id[pId] = qId
self.sz[qId] += self.sz[pId]
else:
self.id[qId] = pId
self.sz[pId] += self.sz[qId]
self.count -= 1


if __name__ == '__main__':
import sys

n = int(sys.stdin.readline())
uf = UF(n)
for line in sys.stdin:
p, q = [int(i) for i in line.split()]
if (uf.connected(p, q)):
continue
else:
uf.union(p, q)
print("%s %s" % (p, q))
print(uf.count, "components")

0 comments on commit 6c55d9e

Please sign in to comment.