220v
젝무의 개발새발
220v
전체 방문자
오늘
어제
  • 분류 전체보기 (255)
    • AI (35)
      • ML, DL 학습 (30)
      • 논문 리뷰 (4)
      • 실습 및 프로젝트 (1)
    • Algorithm (145)
      • LeetCode (13)
      • 프로그래머스 (35)
      • 백준 (96)
      • 알고리즘, 문법 정리 (1)
    • Mobile, Application (17)
      • Flutter (10)
      • iOS, MacOS (7)
    • BackEnd (7)
      • Flask (1)
      • Node.js (5)
      • Spring, JSP..etc (1)
    • Web - FrontEnd (18)
      • JavaScript, JQuery, HTML, C.. (12)
      • React (6)
    • DataBase (1)
      • MySQL (1)
      • Firebase Firestore (0)
      • Supabase (0)
    • Git (1)
    • 기타 툴 및 오류 해결 (3)
    • 강의 (5)
      • Database (3)
      • 암호학 (2)
      • 알고리즘 (0)
    • 후기와 회고 (2)
    • 블로그 꾸미기 (1)
    • 일상과 이것저것 (20)
      • 맛집 (12)
      • 세상사는일 (4)
      • 도서리뷰 (1)
      • 이런저런 생각들 (잡글) (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Prefix Sum
  • Dynamic Programming
  • REACT
  • simulation
  • dp
  • 구현
  • BFS
  • 백준
  • 다익스트라
  • 오블완
  • dfs
  • Minimum Spanning Tree
  • brute-Force
  • 위상 정렬
  • 프로그래머스
  • implementation
  • binary search
  • union-find
  • bitmasking
  • Priority Queue
  • disjoint set
  • IMPLEMENT
  • Backtracking
  • topological sort
  • Lis
  • two pointer
  • top-down
  • Mathematics
  • 티스토리챌린지
  • Greedy

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Algorithm/백준

[백준] 3584. 가장 가까운 공통 조상 - Python

2023. 11. 13. 00:34

[Gold IV]

 

https://www.acmicpc.net/problem/3584

 

3584번: 가장 가까운 공통 조상

루트가 있는 트리(rooted tree)가 주어지고, 그 트리 상의 두 정점이 주어질 때 그들의 가장 가까운 공통 조상(Nearest Common Anscestor)은 다음과 같이 정의됩니다. 두 노드의 가장 가까운 공통 조상은, 두

www.acmicpc.net

 

풀이

처음 보는 LCA (Lowest Common Ancestor) 문제.

DFS를 통해 Root 노드부터 각 노드의 깊이(depth)를 저장하고,

입력된 두 노드의 depth를 맞춘 후, 공통 조상이 나올 때까지 그대로 거슬러 올라가는 식으로 해결하였다.

 

이 풀이의 경우 O(N)의 Time Complexity로 해결한 경우이며,

개선된 LCA 알고리즘의 경우 O(logN) 의 복잡도로 해결할 수 있다고 한다.

LCA 알고리즘에 대해서는 여러 곳에서 잘 설명해 놓았으니, 이 곳에는 따로 적지 않겠다.

 

AC.

import sys
sys.setrecursionlimit(int(1e5))

T = int(input())

for _ in range(T):
    N = int(input())
    parent = [0] * (N+1)
    depth = [0] * (N+1)
    cal = [False] * (N+1)
    tree = [[] for _ in range(N + 1)]

    for _ in range(N-1):
        a, b = map(int, input().split())
        tree[a].append(b)
        tree[b].append(a)
        parent[b] = a

    # 루트 노드 찾기 (parent가 0(초기값)이면 root)
    root = 0
    for i in range(1, N+1):
        if parent[i] == 0:
            root = i
            
    # 루트 노드부터 depth 저장.
    def dfs(x, dep):
        cal[x] = True
        depth[x] = dep
        for y in tree[x]:
            if cal[y]:
                continue
            parent[y] = x
            dfs(y, dep+1)
    
    # Lowest Common Ancestor
    def LCA(x, y):
        while depth[x] != depth[y]:
            if depth[x] > depth[y]:
                x = parent[x]
            else:
                y = parent[y]
        
        while x != y:
            x = parent[x]
            y = parent[y]
        
        return x

    # root부터 dfs를 통해 depth 저장
    dfs(root, 0)
    
    # LCA
    n, m = map(int, input().split())
    print(LCA(n, m))

 

    'Algorithm/백준' 카테고리의 다른 글
    • [백준] 1194. 달이 차오른다, 가자. - Python
    • [백준] 1948. 임계경로 - Python
    • [백준] 16724. 피리 부는 사나이 - Python
    • [백준] 13164. 행복 유치원 - Python
    220v
    220v
    DGU CSE 20 / Apple Developer Academy @ POSTECH 2nd Jr.Learner.

    티스토리툴바