728x90

 

생각보다는 쉽게 풀었던 문제인데, 

 

from collections import deque
N = int(input())
gp = [[] for _  in range (0,N+1)]
for _ in range (0,N-1):
    a,b = map(int,input().split())
    gp[a].append(b)
    gp[b].append(a)
depth = [[] for _ in range (0,N+1)]
depth[1] = (1,1)
deq = deque()
check = [False for _ in range (0,N+1)]
new_graph = [[] for _ in range (0,N+1)]
deq.append((1,1))
while deq:
    x = deq.popleft()
    x,y = x[0], x[1]
    check[x] = True
    for z in gp[x]:
        if check[z] == False:
            deq.append((z,y + 1))
            new_graph[x].append((z,y+1))
            
ans = [0 for _ in range (0,N+1)]

for i in range (0,N+1):
    if new_graph[i] != []:
        for x in new_graph[i]:
            ans[x[0]] = i

for i in range (2,N+1):
    print(ans[i])

+ Recent posts