https://www.acmicpc.net/problem/1717
1717번: 집합의 표현
초기에 $n+1$개의 집합 $\{0\}, \{1\}, \{2\}, \dots , \{n\}$이 있다. 여기에 합집합 연산과, 두 원소가 같은 집합에 포함되어 있는지를 확인하는 연산을 수행하려고 한다. 집합을 표현하는 프로그램을 작
www.acmicpc.net
아이디어
union-find로 풀었다.
시간 초과가 나서 계속 찾아봤는데 input 함수를 sys.stdin.readline으로 변경해주어야 했다..
전체 코드
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
def find(x):
if parents[x] != x:
parents[x] = find(parents[x])
return parents[x]
def union(a, b):
a = find(a)
b = find(b)
if a < b:
parents[b] = a
else:
parents[a] = b
n , m = map(int, input().split())
parents = [x for x in range(n + 1)]
for _ in range(m):
c, a, b = map(int, input().split())
if c == 0:
union(a, b)
else:
if find(a) == find(b):
print("YES")
else:
print("NO")
'Coding Test > Python' 카테고리의 다른 글
[백준/구현&정렬] 8978번: 올림픽 (python, 실버5 ) (0) | 2024.03.12 |
---|---|
[백준/BFS&DFS] 1926번: 그림 (python, 실버 1) (0) | 2024.03.11 |
[LeetCode] 47. Permutations II (Medium, Python) (1) | 2024.02.14 |
[LeetCode] 46. Permutations (Medium, Python) (0) | 2024.02.14 |
[백준/구현] 20057번: 마법사 상어와 토네이도(골드3, python) (1) | 2024.02.09 |