Skip to content

Instantly share code, notes, and snippets.

@thbighead
Created May 7, 2017 00:20
Show Gist options
  • Save thbighead/5fb511694f70e18da7f5642ce84b6d24 to your computer and use it in GitHub Desktop.
Save thbighead/5fb511694f70e18da7f5642ce84b6d24 to your computer and use it in GitHub Desktop.
disjoint sets meio torto escrito em Python (o que eu fiz em C eh que eh o bicho!)
sets = {}
setsRanked = {}
def makeSet(x):
sets[x] = set([x])
def find(x):
for representative,subset in sets.iteritems():
if x in subset:
return representative
return None
def union(x, y):
xRepresentative = find(x)
yRepresentative = find(y)
sets[yRepresentative] = sets[yRepresentative].union(sets[xRepresentative])
del sets[xRepresentative]
def makeSetWithRank(x):
setsRanked[x] = [set([x]), 0]
# naum faz path compression na real, foi soh para criar um outro find pros setsRanked
def findWithPathCompression(x):
for representative,subsetRanked in setsRanked.iteritems():
if x in subsetRanked[0]:
return representative
return None
def unionByRank(x, y):
xRepresentative = findWithPathCompression(x)
yRepresentative = findWithPathCompression(y)
if xRepresentative != yRepresentative:
if setsRanked[xRepresentative][1] < setsRanked[yRepresentative][1]:
setsRanked[xRepresentative][0] = setsRanked[xRepresentative][0].union(setsRanked[yRepresentative][0])
del setsRanked[yRepresentative]
elif setsRanked[xRepresentative][1] > setsRanked[yRepresentative][1]:
setsRanked[yRepresentative][0] = setsRanked[yRepresentative][0].union(setsRanked[xRepresentative][0])
del setsRanked[xRepresentative]
else:
setsRanked[yRepresentative][0] = setsRanked[yRepresentative][0].union(setsRanked[xRepresentative][0])
setsRanked[yRepresentative][1] += 1
del setsRanked[xRepresentative]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment