最近公共祖先
仅仅记录板子
#include<bits/stdc++.h>
#define ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pii pair<int,int>
using namespace std;
const int N = 5e5+10, M = 2*N;
int n, m, s;
int e[M], nex[M], h[N], idx;
int depth[N], fa[N][30];
void add(int a, int b){
e[++idx] = b;
nex[idx] = h[a];
h[a] = idx;
}
void dfs(int x, int f){
depth[x] = depth[f] + 1;
fa[x][0] = f;
for(int i = 1;i <= 20;i++){
fa[x][i] = fa[fa[x][i-1]][i-1];
}
for(int i = h[x]; ~i; i = nex[i]){
if(e[i] != f){
dfs(e[i], x);
}
}
}
int getRes(int x, int y){
for(int i = 20;i >= 0;i--){
if(depth[fa[x][i]] >= depth[y]){
x = fa[x][i];
}
}
return x;
}
int LCA(int x, int y){
if(depth[x] < depth[y])swap(x, y);
x = getRes(x, y);
if(x == y)return y;
for(int i = 20;i >= 0;i--){
if(fa[x][i] != fa[y][i]){
x = fa[x][i];
y = fa[y][i];
}
}
return fa[x][0];
}
int main(){
ios;
string c = "P3379_1.in";
// freopen(c.c_str(),"r",stdin);
memset(h, -1, sizeof h);
cin >> n >> m >> s;
for(int i = 0;i < n-1;i++){
int x, y;
cin >> x >> y;
add(x, y);
add(y, x);
}
dfs(s, 0);
for(int i = 0;i < m;i++){
int x, y;
cin >> x >> y;
cout << LCA(x, y) << "\n";
}
// fclose(stdin);
return 0;
}