# 【算法小结】倍增算法求LCA

【模板】最近公共祖先（LCA） - 洛谷

``````#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5;
struct node {
int v, ne;
}e[N<<1];
int head[N], cnt, lg[N], fa[N][30], depth[N];
void add(int x, int y) {
e[++cnt].v = y;
}
void dfs(int now, int fath) {
fa[now][0] = fath; depth[now] = depth[fath] + 1;
for (int i = 1; i <= lg[depth[now]]; i++) fa[now][i] = fa[fa[now][i - 1]][i - 1];
for (int i = head[now]; i != 0; i = e[i].ne) {
if (e[i].v != fath) dfs(e[i].v, now);
}
}
int LCA(int x, int y) {
if (depth[x] < depth[y]) swap(x, y);
while (depth[x] > depth[y]) x = fa[x][lg[depth[x] - depth[y]]];
if (x == y) return x;
for (int k = lg[depth[x]]; k >= 0; k--) {
if (fa[x][k] != fa[y][k]) x = fa[x][k], y = fa[y][k];
}
return fa[x][0];
}
int main() {
int n, m, s; cin >> n >> m >> s;
for (int i = 1; i <= n - 1; i++) {
int u, v; cin >> u >> v;
}
lg[0] = -1; for (int i = 1; i <= n; i++) lg[i] = lg[i >> 1] + 1;
dfs(s, 0);
for (int i = 1; i <= m; i++) {
int x, y; cin >> x >> y;
cout << LCA(x, y) << endl;
}
return 0;
}``````

https://blog.csdn.net/m0_62434776/article/details/126139962

Scroll to Top