forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5.py
More file actions
46 lines (38 loc) Β· 1.22 KB
/
Copy path5.py
File metadata and controls
46 lines (38 loc) Β· 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import sys
sys.setrecursionlimit(int(1e5)) # λ°νμ μ€λ₯λ₯Ό νΌνκΈ° μν μ¬κ· κΉμ΄ μ ν μ€μ
n = int(input())
parent = [0] * (n + 1) # λΆλͺ¨ λ
Έλ μ 보
d = [0] * (n + 1) # κ° λ
ΈλκΉμ§μ κΉμ΄
c = [0] * (n + 1) # κ° λ
Έλμ κΉμ΄κ° κ³μ°λμλμ§ μ¬λΆ
graph = [[] for _ in range(n + 1)] # κ·Έλν(graph) μ 보
for _ in range(n - 1):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
# λ£¨νΈ λ
ΈλλΆν° μμνμ¬ κΉμ΄(depth)λ₯Ό ꡬνλ ν¨μ
def dfs(x, depth):
c[x] = True
d[x] = depth
for y in graph[x]:
if c[y]: # μ΄λ―Έ κΉμ΄λ₯Ό ꡬνλ€λ©΄ λκΈ°κΈ°
continue
parent[y] = x
dfs(y, depth + 1)
# Aμ Bμ μ΅μ κ³΅ν΅ μ‘°μμ μ°Ύλ ν¨μ
def lca(a, b):
# λ¨Όμ κΉμ΄(depth)κ° λμΌνλλ‘
while d[a] != d[b]:
if d[a] > d[b]:
a = parent[a]
else:
b = parent[b]
# λ
Έλκ° κ°μμ§λλ‘
while a != b:
a = parent[a]
b = parent[b]
return a
dfs(1, 0) # λ£¨νΈ λ
Έλλ 1λ² λ
Έλ
m = int(input())
for i in range(m):
a, b = map(int, input().split())
print(lca(a, b))