Created
February 7, 2014 11:56
-
-
Save pdparker/8861430 to your computer and use it in GitHub Desktop.
Quick Find and Union
This file contains 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 Quick: | |
def __init__(self,x): | |
self.ids = {i:i for i in x} | |
self.node = self.ids.keys() | |
self.connect = self.ids.values() | |
self.sz = {i:1 for i in range(len(self.ids))} | |
def root(self, x,compression=True): | |
while x != self.ids[x]: | |
if compression==True: | |
self.ids[x] = self.ids[self.ids[x]] | |
x = self.ids[x] | |
else: | |
x = self.ids[x] | |
return x | |
def union(self, x,y, method): | |
if method == quickFind: | |
self.quickFind(x,y) | |
elif method == simpleUnion: | |
self.simpleUnion(x,y) | |
elif method == self.weightedUnion: | |
self.weightedUnion(x,y) | |
elif method == compressionUnion: | |
self.compressionUnion(x,y) | |
#———Union and Find methods——— | |
def quickFind(self, x,y): | |
if x > y: | |
for k, v in self.ids.iteritems(): | |
if v is y: | |
self.ids[k] = x | |
else: | |
for k, v in self.ids.iteritems(): | |
if v is x: | |
self.ids[k] = y | |
def simpleUnion(self,x,y): | |
i = self.root(x, False) | |
j = self.root(y, False) | |
self.ids[i] = j | |
def weightedUnion(self,x,y): | |
i = self.root(x, False) | |
j = self.root(y, False) | |
if self.sz[i]< self.sz[j]: | |
self.ids[i]=j | |
self.sz[j] += self.sz[i] | |
else: | |
self.ids[j]=i | |
self.sz[i] += self.sz[j] | |
def compressionUnion(self, x,y): | |
i = self.root(x, True) | |
j = self.root(y, True) | |
if self.sz[i]< self.sz[j]: | |
self.ids[i]=j | |
self.sz[j] += self.sz[i] | |
else: | |
self.ids[j]=i | |
self.sz[i] += self.sz[j] | |
def simpleConnect (self,x,y): | |
return self.ids[x] == self.ids[y] | |
def rootConnect (self, x,y,compression=True): | |
return self.root(self.ids[x],compression) == self.root(self.ids[y], compression) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment