생각보다는 쉽게 풀었던 문제인데,
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])
'코딩' 카테고리의 다른 글
[BOJ,백준] 1198 삼각형으로 자르기 python (0) | 2024.05.13 |
---|---|
[BOJ,백준] 20920 영단어 암기는 괴로워 (0) | 2024.05.12 |
[BOJ] 14503 로봇 청소기 python (0) | 2024.04.12 |
[BOJ] 15683 감시 python (0) | 2024.04.10 |
[BOJ] 14888 연산자 끼워넣기 python (0) | 2024.04.09 |