Scribbling

서로소 집합 알고리즘 본문

Computer Science/Algorithms & Data Structures

서로소 집합 알고리즘

focalpoint 2021. 8. 12. 14:38
v, e = map(int, input().split())
edges = []
for _ in range(e):
    edges.append(list(map(int, input().split())))

parent = [0] * (v+1)
for i in range(v+1):
    parent[i] = i

def find_parent(parent, a):
    if parent[a] == a:
        return a
    else:
        parent[a] = find_parent(parent, parent[a])
        return parent[a]

def union(parent, a, b):
    a = find_parent(parent, a)
    b = find_parent(parent, b)
    if a < b:
        parent[b] = a
    else:
        parent[a] = b

for u, v in edges:
    union_parent(parent, u, v)

for i in range(v):
    find_parent(parent, i)

for i in range(1, v):
    print(parent[i])