LCA(最近公共祖先)代码
C++#include <bits/stdc++.h>
#define int long long
const int ONE = 1000010;//长度
using namespace std;
int nxt[ONE * 2], head[ONE * 2], to[ONE * 2];
int Dep[ONE], f[ONE][21];
int tot; //边的个数
void add(int u, int v) { //建边
nxt[++tot] = head[u];
head[u] = tot;
to[tot] = v;
}
void Deal_head(int u, int father) { //预处理
Dep[u] = Dep[father] + 1;
for (int i = 0; i <= 19; i++) {
f[u][i + 1] = f[f[u][i]][i];
}
for (int i = head[u]; i; i = nxt[i]) {
int v = to[i];
if (v == father) continue;
f[v][0] = u; // v向上跳2^0=1就是u
Deal_head(v, u);
}
}
int LCA(int x, int y) {
if (Dep[x] < Dep[y]) swap(x, y); //让x深度较大
//我们用"暴力"的思想:先将x,y跳到同一深度,然后一起往上跳
for (int i = 20; i >= 0; i--) { //一定要down to!一定要down to!一定要down to!
//防止"反悔"
if (Dep[f[x][i]] >= Dep[y]) x = f[x][i]; //先跳到同一层
if (x == y) return x;
}
//此时x,y已跳到同一层
for (int i = 20; i >= 0; i--) {
if (f[x][i] != f[y][i]) { //如果f[x][i]和f[y][i]不同才跳
x = f[x][i];
y = f[y][i];
}
}
return f[x][0];
}
signed main() {
int node_number, question_number, root_number;
cin>> node_number >> question_number >> root;
for (int i = 1; i < node_number; i++) {
int node1, node2;
cin >> node1 >> node2;
add(node1, node2);
add(node2, node1);
}
// cout << "1\n";
Deal_head(root_number, 0);
while (question_number--) {
int x, y;
cin >> x >>y;
// cout << Dep[LCA(x, y)] << ' ';
cout<< LCA(x,y) << '\n';
}
}