코딩테스트 준비/[백준]

[백준] LCA(Lowest Common Ancestor) 11437 최소 공통 조상

bled 2021. 12. 18. 08:20

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

 

11437번: LCA

첫째 줄에 노드의 개수 N이 주어지고, 다음 N-1개 줄에는 트리 상에서 연결된 두 정점이 주어진다. 그 다음 줄에는 가장 가까운 공통 조상을 알고싶은 쌍의 개수 M이 주어지고, 다음 M개 줄에는 정

www.acmicpc.net

 

import sys
sys.setrecursionlimit(int(1e5))
input = sys.stdin.readline

n = int(input())
graph = [[] for _ in range(n+1)]
depth_list = [0] * (n+1)
visited = [False] * (n+1)
parent = [0] * (n+1)

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

def dfs(x, depth):
    visited[x] = True
    depth_list[x] = depth
    for next_node in graph[x]:
        if visited[next_node]:
            continue
        parent[next_node] = x
        dfs(next_node, depth+1)

def lca(a, b):
    while depth_list[a] != depth_list[b]:
        if depth_list[a] > depth_list[b]:
            a = parent[a]
        else:
            b = parent[b]
    while a != b:
        a = parent[a]
        b = parent[b]
    return a


dfs(1, 0)

m = int(input())
for _ in range(m):
    a, b = map(int, input().split())
    print(lca(a, b))