목차

LCA 2

ps
링크acmicpc.net/…
출처BOJ
문제 번호11438
문제명LCA 2
레벨플래티넘 5
분류

LCA

시간복잡도O(n+qlogn)
인풋사이즈n<=100,000, q<=100,000
사용한 언어Python
제출기록57828KB / 740ms
최고기록740ms
해결날짜2022/12/01

풀이

코드

"""Solution code for "BOJ 11438. LCA 2".

- Problem link: https://www.acmicpc.net/problem/11438
- Solution link: http://www.teferi.net/ps/problems/boj/11438

Tags: [LCA]
"""

import sys
from teflib import tree as ttree

ROOT = 0


def main():
    N = int(sys.stdin.readline())
    tree = [[] for _ in range(N)]
    for _ in range(N - 1):
        u, v = [int(x) for x in sys.stdin.readline().split()]
        tree[u - 1].append(v - 1)
        tree[v - 1].append(u - 1)

    lca = ttree.LowestCommonAncestor(tree, ROOT)
    M = int(sys.stdin.readline())
    for _ in range(M):
        u, v = [int(x) for x in sys.stdin.readline().split()]
        print(lca.lca_node(u - 1, v - 1) + 1)


if __name__ == '__main__':
    main()