Created
May 6, 2017 15:25
-
-
Save shivangg/ae28bb428dd607bce1f6292d08ed45ea to your computer and use it in GitHub Desktop.
Union Find algorithm with improved quick union implementation
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
n, m = input().strip().split(' ') | |
n, m = [int(n), int(m)] | |
id = [i for i in range(n+1)] | |
def rootParent(i): | |
commonGeneration = [] | |
while(id[i] is not i): | |
# print(i, id[i]) | |
commonGeneration.append(i) | |
i = id[i] | |
# print( "commonGeneration" ,str(commonGeneration)) | |
for x in range(len(commonGeneration)): | |
id[commonGeneration[x]] = id[i] | |
return i | |
for route_i in range(m): | |
a, b = input().split() | |
a, b = int(a), int(b) | |
# make the parent of i is id[i] | |
# the bigger one is the parent | |
if b > a : | |
temp = a | |
a = b | |
b = temp | |
# change the root of id[a] to root of b | |
id[rootParent(id[a])] = rootParent(b) | |
for i in range(len(id)): | |
id[i] = rootParent(id[i]) | |
# print([x for x in range(n+1)]) | |
# print(id) | |
d= {} | |
for x in range(len(id)): | |
k = id[x] | |
if k not in d: | |
d[k] = 1 | |
else: | |
d[k] += 1 | |
# print((d)) | |
d_values = list(d.values()) | |
d_keys = list(d.keys()) | |
print(max(d_values)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment