# Coding/# 백준

[백준 / 11725] 트리의 부모 찾기 - Python

강현들 2021. 7. 7. 13:04
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
반응형