union- find를 통해 집합을 나누고 group의 크기를 측정해 출력해줬습니다.
def find(x):
if parents[x] == x:
return x
parents[x] = find(parents[x])
return parents[x]
def union(x, y):
x = find(x)
y = find(y)
if x > y:
x, y = y, x
parents[y] = x
for test in range(1, int(input()) + 1):
N, M = map(int, input().split())
prefer_set = list(map(int, input().split()))
parents = {i: i for i in range(1, N + 1)}
for i in range(M):
a, b = prefer_set[i * 2], prefer_set[i * 2 + 1]
if find(a) != find(b):
union(a, b)
group = set()
for i in range(1, N + 1):
if parents[i] not in group:
x = find(i)
if x not in group:
group.add(x)
print(f'#{test} {len(group)}')
'practivceAlgorithm > swexpertacademy' 카테고리의 다른 글
[SWEA][Python] 1486 장훈이의 높은 선반 (0) | 2021.10.08 |
---|---|
[SWEA][Python] 1865 동철이의 일 분배 (0) | 2021.10.07 |
[SWEA][Python] 5247 연산 (0) | 2021.10.06 |
[SWEA][Python] 5209 최소 생산 비용 (0) | 2021.10.06 |
[SWEA][Python] 5208 전기버스2 (0) | 2021.10.06 |