1976-g4 성공
This commit is contained in:
51
workbook_8708/gold/1976-g4.py
Normal file
51
workbook_8708/gold/1976-g4.py
Normal file
@@ -0,0 +1,51 @@
|
||||
# 여행가자
|
||||
|
||||
import sys
|
||||
from collections import deque
|
||||
|
||||
input = sys.stdin.readline
|
||||
|
||||
def solution():
|
||||
n = int(input().rstrip())
|
||||
m = int(input().rstrip())
|
||||
|
||||
g = {}
|
||||
for i in range(n):
|
||||
info = list(map(int, input().rstrip().split()))
|
||||
g[i+1] = [idx+1 for idx, con in enumerate(info) if con == 1]
|
||||
|
||||
plan = list(map(int, input().rstrip().split()))
|
||||
visited = [0] * (n+1)
|
||||
q = deque([plan[0]])
|
||||
visited[plan[0]] = 1
|
||||
while q:
|
||||
now = q.popleft()
|
||||
for city in g[now]:
|
||||
if visited[city]:
|
||||
continue
|
||||
q.append(city)
|
||||
visited[city] = 1
|
||||
|
||||
for city in plan:
|
||||
if visited[city] == 0:
|
||||
print("NO")
|
||||
break
|
||||
else:
|
||||
print("YES")
|
||||
|
||||
return
|
||||
|
||||
|
||||
solution()
|
||||
|
||||
"""
|
||||
걸린 시간: 17분
|
||||
|
||||
시간 복잡도: 한 노드당 큐에 한번만 들어오고 나가기 때문에 O(n)인데, 문제는 시작할 때 각 노드마다 연결된 데이터를 읽는 것이
|
||||
O(n^2)이다.
|
||||
|
||||
해설: 뭐가 됐든 시작 도시를 기준으로 하나의 그룹으로 묶여 있으면 된다. 즉 bfs를 진행해서 한 묶음에만 있으면 된다.
|
||||
다른 풀이로 union-find도 있다.
|
||||
공통 조상으로 묶는 방식인데, find 함수는 parent 리스트에서 본인이 parent가 아니면 계속 재귀로 최초 조상을 찾는 것이다.
|
||||
union은 두 노드의 최초 조상을 찾아서 다르면 한쪽으로 편입 시키는 방식이다. 근데 이것도 O(n^2)이다.
|
||||
"""
|
||||
Reference in New Issue
Block a user