Skip to content

Commit

Permalink
[Add] 서로소 알고리즘 (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
heerucan committed Mar 27, 2022
1 parent 9086500 commit 2b44f08
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions CodingTest/CH10 그래프 이론/서로소알고리즘.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
def find_parent(parent, x):
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]

# 두 원소가 속한 집합을 합치기
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b

# 노드와 간선 개수 입력받기
v, e = map(int, input().split())
parent = [0]*(v+1) #부모 테이블 초기화

# 부모 테이블 상에서, 부모를 자기 자신으로 초기화
for i in range(1, v+1):
parent[i] = i

# union 연산을 각각 수행
for i in range(e):
a, b = map(int, input().split())
union_parent(parent, a, b)

# 각 원소가 속한 집합 출력
print('각 원소가 속한 집합: ', end=' ')
for i in range(1, v+1):
print(find_parent(parent, i), end=' ')

print()

# 부모 테이블 내용 출력
print('부모 테이블: ', end=' ')
for i in range(1, v+1):
print(parent[i], end=' ')

0 comments on commit 2b44f08

Please sign in to comment.