From 53681fa79033a87f296da0e6fdfec3e4db62153d Mon Sep 17 00:00:00 2001 From: keunho Date: Sun, 3 Nov 2024 21:58:03 +0900 Subject: [PATCH] 5-kokeunho --- kokeunho/README.md | 5 +- .../\355\212\270\353\246\254/5-kokeunho.py" | 58 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 "kokeunho/\355\212\270\353\246\254/5-kokeunho.py" diff --git a/kokeunho/README.md b/kokeunho/README.md index 20d71ca..114f14a 100644 --- a/kokeunho/README.md +++ b/kokeunho/README.md @@ -3,5 +3,8 @@ | 차시 | 날짜 | 문제유형 | 링크 | 풀이 | |:----:|:---------:|:----:|:-----:|:----:| | 1차시 | 2024.09.28 | 구현 | [킹](https://www.acmicpc.net/problem/1063) | [#1](https://github.com/AlgoLeadMe/AlgoLeadMe-12/pull/1) | -| 2차시 | 2024.10.01 | 다이나믹 프로그래밍 | [평범한 배낭](https://www.acmicpc.net/problem/12865) | [#5] (https://github.com/AlgoLeadMe/AlgoLeadMe-12/pulls/4) | +| 2차시 | 2024.10.01 | 다이나믹 프로그래밍 | [평범한 배낭](https://www.acmicpc.net/problem/12865) | [#5](https://github.com/AlgoLeadMe/AlgoLeadMe-12/pull/5) | +| 3차시 | 2024.10.08 | 구현 | [약수들의 합](https://www.acmicpc.net/problem/9506) | [#14](https://github.com/AlgoLeadMe/AlgoLeadMe-12/pulls/14) | +| 4차시 | 2024.10.17 | 수학 | [피보나치 수 3](https://www.acmicpc.net/problem/2749) | [#16](https://github.com/AlgoLeadMe/AlgoLeadMe-12/pull/16) | +| 5차시 | 2024.11.03 | 트리 | [LCA](https://www.acmicpc.net/problem/11437) | [#19](https://github.com/AlgoLeadMe/AlgoLeadMe-12/pull/19) | --- diff --git "a/kokeunho/\355\212\270\353\246\254/5-kokeunho.py" "b/kokeunho/\355\212\270\353\246\254/5-kokeunho.py" new file mode 100644 index 0000000..dcd5c8b --- /dev/null +++ "b/kokeunho/\355\212\270\353\246\254/5-kokeunho.py" @@ -0,0 +1,58 @@ +import sys +input = sys.stdin.readline +sys.setrecursionlimit(10**5) + +n = int(input()) + +tree = [[] for _ in range(n+1)] +parent = [[0] * 20 for _ in range(n+1)] +depth = [0] * (n+1) +visited = [False] * (n+1) + +for _ in range(n-1): + p, c = map(int, input().split()) + tree[p].append(c) + tree[c].append(p) + +def dfs(node, d): + visited[node] = True + depth[node] = d + for i in tree[node]: + if not visited[i]: + parent[i][0] = node + dfs(i, d + 1) + +def sparse_table(): + for j in range(1, 20): + for i in range(1, n+1): + if parent[i][j-1] != 0: + parent[i][j] = parent[parent[i][j-1]][j-1] + +def lca(a, b): + if depth[a] < depth[b]: + a, b = b, a + + for i in range(19, -1, -1): + if depth[a] - depth[b] >= (1 << i): + a = parent[a][i] + + if a == b: + return a + + for i in range(19, -1, -1): + if parent[a][i] != parent[b][i]: + a = parent[a][i] + b = parent[b][i] + + return parent[a][0] + +dfs(1, 0) +sparse_table() + +m = int(input()) + +for _ in range(m): + a, b = map(int, input().split()) + print(lca(a, b)) + + \ No newline at end of file