Skip to content

Commit

Permalink
5-kokeunho
Browse files Browse the repository at this point in the history
  • Loading branch information
kokeunho committed Nov 3, 2024
1 parent fbf0be5 commit 53681fa
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
5 changes: 4 additions & 1 deletion kokeunho/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
---
58 changes: 58 additions & 0 deletions kokeunho/트리/5-kokeunho.py
Original file line number Diff line number Diff line change
@@ -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))


0 comments on commit 53681fa

Please sign in to comment.