Skip to content

Commit 5c1a49e

Browse files
committed
[BOJ] 트리의 부모 찾기 / 실버2 / 60분
https://www.acmicpc.net/problem/11725
1 parent 8fbc3c3 commit 5c1a49e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from collections import deque, defaultdict
2+
3+
def bfs(graph, start_node, n, answer):
4+
queue = deque([start_node])
5+
visited = [False] * n
6+
visited[start_node] = True
7+
8+
while queue:
9+
current_node = queue.popleft()
10+
11+
for next_node in graph[current_node]:
12+
if not visited[next_node]:
13+
queue.append(next_node)
14+
visited[next_node] = True
15+
answer[next_node] = current_node
16+
17+
return answer
18+
19+
# 입력값 받기
20+
n = int(input())
21+
edges = [list(map(int, input().split())) for _ in range(n - 1)]
22+
23+
# 그래프 초기화 (인접 리스트 사용)
24+
graph = defaultdict(list)
25+
26+
for edge in edges:
27+
node1, node2 = edge
28+
graph[node1 - 1].append(node2 - 1)
29+
graph[node2 - 1].append(node1 - 1)
30+
31+
# 정답 배열 초기화
32+
answer = [0] * n
33+
34+
# BFS 실행 (0번 노드를 루트로 설정)
35+
answer = bfs(graph, 0, n, answer)
36+
37+
# 결과 출력 (루트 노드를 제외한 노드들의 부모 노드를 출력)
38+
for parent in answer[1:]:
39+
print(parent + 1)

0 commit comments

Comments
 (0)