Skip to content

Commit 610e616

Browse files
committed
upload files
1 parent dfb6aaa commit 610e616

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# LCA 알고리즘 (Lowest Common Ancestor)
2+
# 푼 방식 : 1. 노드의 부모를 각각 값에 넣는다. 2. 루트에서 자신까지 내려오기까지 저장해 2개의 큐를 비교하면서 일치하지 않을 때를 리턴한다.
3+
from collections import deque
4+
5+
t = int(input())
6+
7+
for _ in range(t):
8+
9+
n = int(input())
10+
graph = [0 for _ in range(n+1)] # root는 0이 됨.
11+
12+
for i in range(n-1): # 간선 개수(n-1) - 1
13+
a, b = map(int, input().split())
14+
graph[b] = a # b의 부모는 a
15+
16+
x, y = map(int, input().split())
17+
18+
x_parents = []
19+
i = x
20+
while i:
21+
x_parents.append(i)
22+
i = graph[i]
23+
24+
j = y
25+
while j:
26+
if j in x_parents:
27+
break
28+
j = graph[j]
29+
30+
print(j)

0 commit comments

Comments
 (0)