일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- django
- programmers
- graph
- Algorithm
- 그래프
- 완전탐색
- sort
- Greedy
- 프로그래머스
- 백준
- Brute Force
- 코딩테스트
- 힙
- string
- 탐욕법
- 큐
- 문자열
- 동적계획법
- DFS
- 알고리즘
- 정렬
- binary search
- 카카오 기출
- Code Refactoring
- heap
- Queue
- DP
- DVWA
- Dynamic Programming
- BFS
Archives
- Today
- Total
생각과 고민이 담긴 코드
백준 - 트리의 부모 찾기 (DFS, BFS) / Silver 2 / 11725번 본문
문제 : https://www.acmicpc.net/problem/11725
11725번: 트리의 부모 찾기
루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
www.acmicpc.net
풀이
import sys
from collections import defaultdict
from collections import deque
n = int(sys.stdin.readline())
tree = defaultdict(list)
for _ in range(n - 1):
edge = sys.stdin.readline().split()
tree[edge[0]].append(edge[1])
tree[edge[1]].append(edge[0])
queue = deque('1')
visited = [0] * n
visited[0] = 1
result = {str(i + 1): 0 for i in range(n)}
while queue:
now = queue.popleft()
for i in tree[now]:
if visited[int(i) - 1] == 0:
result[i] = now
visited[int(i) - 1] = 1
queue.append(i)
for key in result.keys():
if key != '1':
print(result[key])
처음 봤을 땐 되게 쉬운 문제라고 생각했는데
풀이에 실패하여 다른 사람의 풀이를 조금 참고하여 다시 한번 풀어보았다.
먼저 tree라는 dictionary를 만들어 node들의 연결관계를 정의하였다.
또한 result dictionary는 각 node들의 부모 node를 저장해주었다.
그 후 1번 node부터 BFS로 탐색해서 "now" node과 연결된 node들을 처음 방문한다면
현재 node를 "now" node의 부모 node로 저장시켰다. 그리고 자식 node들을 queue에 추가해주었다.
'Algorithm > 백준' 카테고리의 다른 글
백준 - 치킨 배달 (완전 탐색) / Gold 5 / 15686번 (0) | 2021.11.21 |
---|---|
백준 - 연구소 (DFS, BFS, 완전탐색) / Gold 5 / 14502번 (0) | 2021.11.17 |
백준 - 물건 팔기 (정렬, 완전 탐색) / Silver 3 / 1487번 (0) | 2021.11.12 |
백준 - 연산자 끼워넣기 (완전 탐색) / Silver 1 / 14888번 (0) | 2021.11.02 |
백준 - 가장 큰 증가 부분 수열 (Dynamic Programming) / Silver 2 / 11055번 (0) | 2021.10.28 |