int lca(int x, int y) { //用倍增法求lca
if (depth[x] < depth[y]) swap(x, y);
for (int i = 20; i >= 0; i--) {
if (fa[x][i] != 0 && depth[fa[x][i]] >= depth[y])
x = fa[x][i];
}
if (x == y) return x;
for (int i = 20; i >= 0; i--) {
if (fa[x][i] != 0 && fa[y][i] != 0 && fa[x][i] != fa[y][i]) {
x = fa[x][i];
y = fa[y][i];
}
}
return fa[x][0];
}
完整代码:
#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;
const int maxn = 6e5;
int n, m;
int depth[maxn], fa[maxn][21];
bool vis[maxn];
vector<int> vec[maxn];
void dfs(int now, int dep, int father) {
// 预处理深度
if (vis[now]) return;
vis[now] = true;
depth[now] = dep;
fa[now][0] = father;
for (int v : vec[now]) {
dfs(v, dep + 1, now);
}
}
int lca(int x, int y) { //用倍增法求lca
if (depth[x] < depth[y]) swap(x, y);
for (int i = 20; i >= 0; i--) {
if (fa[x][i] != 0 && depth[fa[x][i]] >= depth[y])
x = fa[x][i];
}
if (x == y) return x;
for (int i = 20; i >= 0; i--) {
if (fa[x][i] != 0 && fa[y][i] != 0 && fa[x][i] != fa[y][i]) {
x = fa[x][i];
y = fa[y][i];
}
}
return fa[x][0];
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n-1; i++) {
int a, b;
scanf("%d %d", &a, &b);
vec[a].push_back(b);
vec[b].push_back(a);
}
dfs(1, 1, 0);
for (int j = 1; j <= 20; j++)
for (int i = 1; i <= n; i++)
fa[i][j] = fa[fa[i][j - 1]][j - 1];
for (int i = 1; i <= m; i++) {
int a, b;
scanf("%d %d", &a, &b);
printf("%d\n", lca(a, b);
}
}