
난이도 : 골드 4
유형 : 유니온 파인드
https://www.acmicpc.net/problem/1976
import sys
input = sys.stdin.readline
# 도시 수, 여행 계획 도시 수
n = int(input())
m = int(input())
# 유니온 파인드를 위한 부모 배열
parent = [i for i in range(n + 1)]
# find 연산 - 경로 압축 포함
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
# union 연산
def union(a, b):
root_a = find(a)
root_b = find(b)
if root_a != root_b:
parent[root_b] = root_a
# 인접행렬 입력 받아 union 처리
for i in range(1, n + 1):
row = list(map(int, input().split()))
for j in range(1, n + 1):
if row[j - 1] == 1:
union(i, j)
# 여행 계획
plan = list(map(int, input().split()))
root = find(plan[0])
# 모든 도시가 같은 집합(루트)이면 YES
for city in plan[1:]:
if find(city) != root:
print("NO")
break
else:
print("YES")
유니온 파인드는 연결 요소를 빠르게 관리할 수 있는 좋은 방법이다.
여행 경로에 있는 도시들이 전부 같은 대표 도시를 갖고 있는지만 판단하면 된다