반응형
https://www.acmicpc.net/problem/20040
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
parents = [i for i in range(n)]
def find(parent, x):
if parent[x] == x:
return x
else:
return find(parent, parent[x])
def union(parent, a, b):
a = find(parent, a)
b = find(parent, b)
if a > b:
parent[a] = b
else:
parent[b] = a
for i in range(m):
a, b = map(int, input().split())
if find(parents, a) != find(parents, b):
union(parents, a, b)
else:
print(i+1)
quit()
print(0)
union-find를 이용하면 사이클 여부를 쉽게 확인할 수 있다.
댓글