ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 13038 |
문제명 | Tree |
레벨 | 플래티넘 1 |
분류 |
LCA, 세그먼트 트리 |
시간복잡도 | O(nlogn + qlogn) |
인풋사이즈 | n<=100,000, q<=100,000 |
사용한 언어 | Python 3.11 |
제출기록 | 74424KB / 1196ms |
최고기록 | 1196ms |
해결날짜 | 2023/07/28 |
"""Solution code for "BOJ 13038. Tree".
- Problem link: https://www.acmicpc.net/problem/13038
- Solution link: http://www.teferi.net/ps/problems/boj/13038
Tags: [lca] [segment tree]
"""
import sys
from teflib import tree as ttree
from teflib import fenwicktree
def main():
n = int(sys.stdin.readline())
p = [int(x) - 1 for x in sys.stdin.readline().split()]
tree = [[] for _ in range(n)]
for u, p in enumerate(p, start=1):
tree[u].append(p)
tree[p].append(u)
fenwick = fenwicktree.FenwickTreeForRangeUpdatePointQuery(n)
lca = ttree.LowestCommonAncestor(tree)
subtree_ranges = ttree.euler_tour_technique(tree)
q = int(sys.stdin.readline())
for _ in range(q):
match sys.stdin.readline().split():
case ['1', a, b]:
u, v = int(a) - 1, int(b) - 1
l = lca.lca_node(u, v)
depth_u = lca.depth(u) - fenwick.get(subtree_ranges[u][0])
depth_v = lca.depth(v) - fenwick.get(subtree_ranges[v][0])
depth_l = lca.depth(l) - fenwick.get(subtree_ranges[l][0])
dist = depth_u + depth_v - depth_l - depth_l
print(dist)
case ['2', v]:
node = int(v) - 1
beg, end = subtree_ranges[node]
fenwick.range_update(beg, end, 1)
if __name__ == '__main__':
main()