-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlca2.py
More file actions
60 lines (47 loc) · 1.14 KB
/
lca2.py
File metadata and controls
60 lines (47 loc) · 1.14 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from re import L
import sys
input = sys.stdin.readline
sys.setrecursionlimit(int(1e5))
LOG = 21
n = int(input())
parent = [[0] * LOG for _ in range(n + 1)]
d = [0] * (n + 1)
c = [0] * (n + 1)
graph = [[] for _ in range(n + 1)]
for _ in range(n - 1):
a, b = map(int, input().split())
graph[a].append(b)
def dfs(x, depth):
c[x] = True
d[x] = depth
for y in graph[x]:
if c[y]:
continue
else:
parent[y][0] = x
dfs(y, depth + 1)
def set_parent():
dfs(1, 0)
for i in range(1, LOG):
for j in range(1, n + 1):
parent[j][i] = parent[parent[j][i - 1]][i - 1]
def lca(a, b):
if d[a] > d[b]:
a, b = b, a
for i in range(LOG - 1, -1, -1):
if d[b] - d[a] >= (1<<i):
b = parent[b][i]
if a == b:
return a
for i in range(LOG - 1, -1, -1):
if parent[a][i] != parent[b][i]:
a = parent[a][i]
b = parent[b][i]
return parent[a][0]
def solve():
set_parent()
m = int(input())
for i in range(m):
a, b = map(int, input().split())
print(lca(a, b))
solve()