- Notifications
You must be signed in to change notification settings - Fork 845
/
Copy path1.py
45 lines (38 loc) · 1.39 KB
/
1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 특정 원소가 속한 집합을 찾기
deffind_parent(parent, x):
# 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출
ifparent[x] !=x:
parent[x] =find_parent(parent, parent[x])
returnparent[x]
# 두 원소가 속한 집합을 합치기
defunion_parent(parent, a, b):
a=find_parent(parent, a)
b=find_parent(parent, b)
ifa<b:
parent[b] =a
else:
parent[a] =b
# 여행지의 개수와 여행 계획에 속한 여행지의 개수 입력받기
n, m=map(int, input().split())
parent= [0] * (n+1) # 부모 테이블 초기화
# 부모 테이블상에서, 부모를 자기 자신으로 초기화
foriinrange(1, n+1):
parent[i] =i
# Union 연산을 각각 수행
foriinrange(n):
data=list(map(int, input().split()))
forjinrange(n):
ifdata[j] ==1: # 연결된 경우 합집합(Union) 연산 수행
union_parent(parent, i+1, j+1)
# 여행 계획 입력받기
plan=list(map(int, input().split()))
result=True
# 여행 계획에 속하는 모든 노드의 루트가 동일한지 확인
foriinrange(m-1):
iffind_parent(parent, plan[i]) !=find_parent(parent, plan[i+1]):
result=False
# 여행 계획에 속하는 모든 노드가 서로 연결되어 있는지(루트가 동일한지) 확인
ifresult:
print("YES")
else:
print("NO")