https://www.acmicpc.net/problem/2606
2606번: 바이러스
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어
www.acmicpc.net
1번을 제외한 모든 감염된 컴퓨터
문제 접근
1번을 제외한 감염된 컴퓨터의 수를 출력하면 된다.
dfs, bfs로도 구현이 되지만 union and find로 구현했다.
https://portable-paper.tistory.com/entry/Union-Find-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98
Union & Find 알고리즘
Union & Find union & Find 이라는 알고리즘은 Union과 Find으로 이루어져있다. Union은 합치기 Find는 찾기 두 집합이 같은 집합에 있는지 확인하기위해 트리를 사용해서 하나의 집합에 있는지 확인하는 방
portable-paper.tistory.com
필요한 함수
union: 합치기
find: 부모찾기
checkParent: 부모가 1인지 확인하기
코드
import sys
input = sys.stdin.readline
"""
2606
union find로 구현하면 바로 풀릴듯
"""
def find(x):
if x != parent[x]:
parent[x] = find(parent[x])
return parent[x]
return x
def union(x, y):
x = find(x)
y = find(y)
if x < y: parent[y] = x
else: parent[x] = y
N = int(input())
pair_count = int(input())
parent = [i for i in range(1, N+1)]
for i in range(pair_count):
a, b = map(int,input().split())
union(a, b)
print(parent.count(1))
30616KB 40ms
'백준 > 문제풀이_python' 카테고리의 다른 글
9375 패션왕 신해빈 python (0) | 2022.12.19 |
---|---|
1043 거짓말 python (0) | 2022.12.19 |
262624 빅데이터? 정보보호! python (0) | 2022.12.17 |
1764 듣보잡 _python (0) | 2022.12.16 |
25400 제자리 _python (0) | 2022.12.16 |
댓글