💯Problem Solving

[BOJ] 11725 트리의 부모 찾기

date
Jul 18, 2023
slug
boj-11725
author
status
Public
tags
Python
BOJ
summary
백준 11725번 문제풀이입니다.
type
Post
thumbnail
category
💯Problem Solving
updatedAt
Jul 17, 2023 05:44 PM

문제 링크


문제


루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.

문제풀이


루트부터 호출을 해가면서 BFS로 호출하되
노드를 queue에 넣을때 그때 pop된 node는 부모임을 항상 보장한다.
그래서 queue에 넣을떄 ancestor 배열의 값을 초기화 시켜주면 된다.
 
파이썬 문제풀이 코드
import sys from collections import deque input = sys.stdin.readline N = int(input()) visited = [0] * (N+1) ancestor = [0] * (N+1) arr = [[] for i in range(N+1)] # print(arr) for _ in range(N-1): e, v = tuple(map(int, input().split())) arr[e].append(v) arr[v].append(e) # print(arr) # print(arr) q = deque() q.append(1) def bfs(): while q: node = q.popleft() # print(ancestor) # print(arr[node]) if visited[node]: continue visited[node] = 1 for i in arr[node]: if not visited[i]: q.append(i) ancestor[i] = node bfs() for i in range(2, N+1): print(ancestor[i])
 
시간복잡도
  • O(N)

입력


 

출력


 

예제 입력


7 1 6 6 3 3 5 4 1 2 4 4 7

예제 출력


4 6 1 3 1 4
12 1 2 1 3 2 4 3 5 3 6 4 7 4 8 5 9 5 10 6 11 6 12
1 1 2 3 3 4 4 5 5 6 6

알고리즘 분류