반응형
https://level.goorm.io/exam/49052/%EA%B7%B8%EB%A3%B9-%EC%A7%80%EC%A0%95/quiz/1
구름LEVEL
코딩테스트에서 가장 높은 비중을 차지하는 알고리즘 문제를 제작하고 풀이할 수 있는 온라인 저지 서비스입니다. 기업에서 선호하는 C, C++, 파이썬(Python), 자바(Java), 자바스크립트(Javascript) 이외에 여러 가지 프로그래밍 언어로 풀이할 수 있습니다.
level.goorm.io


union find 문제.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# UTF-8 encoding when using korean | |
import sys | |
def find_parent(x, parent): | |
if x not in parent or x == parent[x]: | |
return x | |
p = find_parent(parent[x], parent) | |
parent[x] = p | |
return p | |
def union_find(x, y, parent): | |
x = find_parent(x, parent) | |
y = find_parent(y, parent) | |
if x != y: | |
parent[y] = x | |
n, m = map(int, sys.stdin.readline().split()) | |
parent = dict() | |
for _ in range(m): | |
a, b = map(int, sys.stdin.readline().split()) | |
# a, b 오름차순으로 변경 | |
if b < a: | |
a, b = b, a | |
# a 학생 기준으로 그룹화 | |
union_find(a, b, parent) | |
print(len(set(find_parent(i, parent) for i in range(1, n+1)))) |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] 백준 17822. 원판 돌리기 (0) | 2020.05.07 |
---|---|
[Python] 프로그래머스. 타일 장식물 (Level 3) (0) | 2020.05.06 |
[Python] 구름. 잡초 제거 (0) | 2020.05.01 |
[Python] 구름. 개구리 2 (0) | 2020.04.29 |
[Python] 구름. 소수 고리 (1) | 2020.04.28 |