알고리즘 공부/백준

(Python)백준 코딩테스트 연습 - 집합의 표현(1717)

HRuler 2023. 8. 7. 00:57

1. 문제

https://www.acmicpc.net/problem/1717

 

1717번: 집합의 표현

초기에 $n+1$개의 집합 $\{0\}, \{1\}, \{2\}, \dots , \{n\}$이 있다. 여기에 합집합 연산과, 두 원소가 같은 집합에 포함되어 있는지를 확인하는 연산을 수행하려고 한다. 집합을 표현하는 프로그램을 작

www.acmicpc.net

2. 풀이

# 1717번 : 집합의 표현
# 입력 코드
import sys
sys.setrecursionlimit(1000000)
input = sys.stdin.readline

# n : 집합 수, m : 연산 수
n, m = map(int, input().split())

# calList : 연산 리스트
calList = [list(map(int, input().split())) for i in range(m)]

# 연산 수행 코드
# setList : 집합 리스트
setList = [i for i in range(n+1)]

def union(a, b):
    aParent = find(a)
    bParent = find(b)
    if aParent < bParent:
        setList[bParent] = aParent
    else:
        setList[aParent] = bParent

def find(child):
    if setList[child] != child:
        setList[child] = find(setList[child])
    
    return setList[child]

for i in calList:
    o, a, b = map(int, i)
    if o == 0:
        union(a, b)
    else:
        if find(a) == find(b):
            print("YES")
        else:
            print("NO")

3. Feedback

 - 반복이 여러번 진행되면서 발생하는 Recursion 에러에서 당연히 에러에 만족할 수 있게 코드를 수정해야 한다고 생각해서 계속 에러가 발생했다.

 때로는 여러번의 반복이 발생할 수밖에 없는 코드가 있을 수도 있다는 생각을 하게되는 코딩 문제였다.