728x90
반응형
https://www.acmicpc.net/problem/11725
11725번: 트리의 부모 찾기
루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
www.acmicpc.net
<전체 코드>
import sys
graph = {}
top = {}
n = int(sys.stdin.readline())
for _ in range(n-1):
x, y = map(int, sys.stdin.readline().split())
if x not in graph:
graph[x] = [y]
else:
graph[x].append(y)
if y not in graph:
graph[y] = [x]
else:
graph[y].append(x)
queue = [1]
while queue:
node = queue.pop(0)
for i in graph[node]:
graph[i].remove(node)
top[i] = node
if len(graph[i]) == 0:
continue
queue.append(i)
for i in range(2, n+1):
print(top[i])
728x90
반응형
'# Coding > # 백준' 카테고리의 다른 글
[백준 / 4811] 알약 - Python (0) | 2021.07.07 |
---|---|
[백준 / 11724] 연결 요소의 개수 - Python (0) | 2021.07.07 |
[백준 / 19238] 스타트 택시 - Python (0) | 2021.07.06 |
[백준 / 1476] 날짜 계산 - Python (0) | 2021.05.26 |
[백준 / 1504] 특정한 최단 경로 - Python (0) | 2021.05.26 |