Notice
Recent Posts
Recent Comments
Link
나의 개발일지
[백준] 11725 트리의 부모 찾기 [Python, 파이썬] 본문
- 문제 : https://www.acmicpc.net/problem/11725
- 🔑 DFS
- 양방향 그래프로 트리를 표현
- 1번 노드부터 출발
- 자식 노드에 도착하면 자식 노드 인덱스에 부모 노드 번호 저장 (answer 리스트)
- DFS 끝나면 answer [2]부터 출력
from collections import defaultdict
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
n = int(input())
tree = defaultdict(list)
for i in range(n-1):
p, c = map(int, input().split())
tree[p].append(c)
tree[c].append(p)
answer = [0] * (n+1)
visit = [0] * (n+1)
visit[1] = 1
def dfs(node):
for c in tree[node]:
if visit[c] == 0:
answer[c] = node
visit[c] = 1
dfs(c)
dfs(1)
for i in range(2, n+1):
print(answer[i])
'백준' 카테고리의 다른 글
[백준] 5557 1학년 [Python, 파이썬] (1) | 2023.10.24 |
---|---|
[백준] 24479 알고리즘 수업 - 깊이 우선 탐색 1 [Python, 파이썬] (1) | 2023.10.21 |
[백준] 16118 달빛 여우 [Python, 파이썬] (1) | 2023.10.21 |
[백준] 1753 최단경로 [Python, 파이썬] (2) | 2023.10.20 |
[백준] 6443 애너그램 [Python, 파이썬] (0) | 2023.10.20 |
Comments