일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 포스코 아카데미
- Brigthics Studio
- 팀 분석
- 혼공머신
- Brightics를 이용한 분석
- Brigthics
- 영상제작기
- 직원 이직률
- 삼성SDS
- 데이터분석
- 삼성SDS Brigthics
- 브라이틱스
- 데이터 분석
- 삼성 SDS Brigthics
- Brightics Studio
- 추천시스템
- 직원 이직여부
- 캐글
- Brigthics를 이용한 분석
- 노코드AI
- 개인 의료비 예측
- 혼공
- 모델링
- 삼성 SDS
- 삼성SDS Brightics
- 혼공머신러닝딥러닝
- Brightics
- 브라이틱스 서포터즈
- 혼공학습단
- 포스코 청년
- Today
- Total
데이터사이언스 기록기📚
[백준/Python] 3584번(DFS, 그래프 이론)_가장 가까운 공통 조상 본문
📌문제 유형
DFS, 그래프 이론 (골드 Lv.4)
📌문제
3584번: 가장 가까운 공통 조상
루트가 있는 트리(rooted tree)가 주어지고, 그 트리 상의 두 정점이 주어질 때 그들의 가장 가까운 공통 조상(Nearest Common Anscestor)은 다음과 같이 정의됩니다. 두 노드의 가장 가까운 공통 조상은, 두
www.acmicpc.net
📌나의 문제풀이
- maps에 B(자식)에 [A(부모)] 저장
- DFS에서 상위 부모들 route에 모두 저장
- route들의 순서 유지한 교집합 구하기
- 해당 방법으로 풀 경우, recursionlimit에 걸리므로 setrecursionlimit을 늘려야 함
# 그래프 이론으로 풀면 recursionlimit 안 늘려도 될 듯
import sys
sys.setrecursionlimit(10**5)
t = int(input())
def dfs(x, route):
if maps[x] != []:
route.append(maps[x])
dfs(maps[x], route)
return route
for _ in range(t):
n = int(input())
# B(자식)에 [A(부모)] 저장
maps = [[] for _ in range(n+1)]
for _ in range(n-1):
a,b = map(int,input().split())
maps[b] = a
# 가까운 공통조상 구할 노드
result_1, result_2 = map(int,input().split())
route1, route2 = [result_1], [result_2]
ans1 = dfs(result_1, route1)
ans2 = dfs(result_2, route2)
# 기존 순서 유지한 교집합 구하기
result = [x for x in ans1 if x in ans2]
print(result[0])
📌 다른사람의 문제풀이
- LCA[백준] 3584번 - 가장 가까운 공통 조상 (파이썬)
# 가장 가까운 공통 조상 def find_parent(parent, x): result = [x] while parent[x]: result.append(parent[x]) x = parent[x] return result T = int(input()) for _ in range(T): N = int(input()) parent = [0 for _ in range(N+1)] for _ in range(N-1): a, b
2hs-rti.tistory.com
# 가장 가까운 공통 조상
def find_parent(parent, x):
result = [x]
while parent[x]:
result.append(parent[x])
x = parent[x]
return result
T = int(input())
for _ in range(T):
N = int(input())
parent = [0 for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
parent[b] = a
x, y = map(int, input().split())
# 각 부모 리스트 정의
x_parent = find_parent(parent, x)
y_parent = find_parent(parent, y)
# 깊이 맞춰주기
i, j = 0, 0
if len(x_parent) > len(y_parent):
i = len(x_parent) - len(y_parent)
else:
j = len(y_parent) - len(x_parent)
# 같은 깊이에서 최소 공통 조상 찾기
while x_parent[i] != y_parent[j]:
i += 1
j += 1
print(x_parent[i])
📌 리뷰
- 관점을 반대로 바라보기(보통은 부모노드에 자식 저장, 이번 경우는 자식 노드에 부모 저장)
- 순서 유지 교집합
순서유지 교집합 - python list ordered intersection
두 리스트의 교집합을 구하는 방법 1. 순서가 필요 없는 경우 : 파이썬의 내장 함수인 Set() 집합 함수를 ...
blog.naver.com
'Coding Test > 백준(Python)' 카테고리의 다른 글
[백준/Python] 13164번(그리디,정렬)_행복 유치원 (0) | 2023.09.05 |
---|---|
[백준/Python] 6593번(BFS)_상범빌딩 (0) | 2023.09.05 |
[백준/Python] 14502번(완탐, DFS)_연구소 (0) | 2023.08.15 |
[백준/Python] 13975번(그리디, 우선순위 큐)_ 파일 합치기3 (0) | 2023.08.09 |
[백준/Python] 1339번(그리디)_단어 수학 (0) | 2023.08.08 |