백준
1. Python
DFS
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)]
for _ in range(n - 1):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
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)
def lca(a, b):
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)
m = int(input())
for i in range(m):
a, b = map(int, input().split())
print(lca(a, b))
2. C++
BFS
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int N, M;
int u, v;
queue<int> q;
vector<int> node[50001];
bool check[50001];
int parent[50001];
int depth[50001];
int LCA(int u, int v)
{
if (depth[u] > depth[v]) swap(u, v);
while (depth[u] != depth[v]) v = parent[v];
while (u != v)
{
u = parent[u];
v = parent[v];
}
return u;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> N;
for (int i = 0; i < N-1; i++)
{
cin >> u >> v;
node[u].push_back(v);
node[v].push_back(u);
}
check[1] = true;
q.push(1);
while (!q.empty())
{
int x = q.front();
q.pop();
for (int i = 0; i < node[x].size(); i++)
{
if (!check[node[x][i]])
{
depth[node[x][i]] = depth[x] + 1;
check[node[x][i]] = true;
parent[node[x][i]] = x;
q.push(node[x][i]);
}
}
}
cin >> M;
for (int i = 0; i < M; i++)
{
cin >> u >> v;
cout << LCA(u, v) << '\n';
}
}