Created
September 1, 2014 23:21
-
-
Save horiajurcut/acd701348002d8077f4a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class QuickFindUF: | |
def __init__(self, n): | |
self.id = [] | |
for i in range(0, n): | |
self.id.append(i) | |
def connected(self, p, q): | |
return self.id[p] == self.id[q] | |
def union(self, p, q): | |
pid = self.id[p] | |
qid = self.id[q] | |
for idx, val in enumerate(self.id): | |
if val == pid: | |
self.id[idx] = qid | |
if __name__ == '__main__': | |
uf = QuickFindUF(10) | |
uf.union(1, 2) | |
uf.union(4, 3) | |
uf.union(3, 4) | |
uf.union(1, 3) | |
print uf.connected(2, 3) | |
print uf.id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment