dfs or bfs or disjoint-set
import sys
input = sys.stdin.readline
def find(x):
if parent[x] == x:
return x
parent[x] = find(parent[x])
return parent[x]
def union(a,b):
a = find(a)
b = find(b)
if level[a] >= level[b]:
parent[b] = a
if level[a]==level[b]:
level[a] += 1
else:
parent[a] = b
N, M = map(int, input().split())
parent = {i: i for i in range(1,N+1)}
level = {i:0 for i in range(1,N+1)}
for _ in range(M):
a, b = map(int, input().split())
if find(a) != find(b):
union(a,b)
cnt = set()
for i in range(1,N+1):
pa = find(i)
if pa not in cnt:
cnt.add(pa)
print(len(cnt))
'practivceAlgorithm > 백준' 카테고리의 다른 글
[백준][Python] 1260 DFS와 BFS (0) | 2021.08.31 |
---|---|
[백준][Python] 18860 좌표압축 (1) | 2021.08.31 |
[백준][Python] 18234 당근훔쳐먹기 (0) | 2021.08.31 |
[백준][Python] 18352 특정거리의 도시찾기 (0) | 2021.08.31 |
[백준][Python] 14442 벽 뿌수고 이동하기2 (1) | 2021.08.30 |