模板:最近公共祖先(LCA)
C++#include <iostream>
#include <queue>
#include <cmath>
#include <vector>
using namespace std;
const int N = 5e5 + 10,M = 30;
int n,m,tot,f[N][M],root,d[N];
vector <int> v[N];
queue <int> q;
inline void bfs(int root)
{
d[root] = 1;
q.push(root);
while (!q.empty())
{
int x = q.front();
q.pop();
for(int i = 0;i < v[x].size();i ++)
{
int g = v[x][i];
if (d[g]) continue;
d[g] = d[x] + 1;
f[g][0] = x;
for(int j = 1;j <= tot;j ++)
f[g][j] = f[f[g][j - 1]][j - 1];
q.push(g);
}
}
}
inline int lca(int x,int y)
{
if (d[x] > d[y]) swap(x,y);
for(int i = tot;i >= 0;i --)
if (d[f[y][i]] >= d[x]) y = f[y][i];
if (x == y) return y;
for(int i = tot;i >= 0;i --)
if (f[x][i] != f[y][i]) x = f[x][i],y = f[y][i];
return f[x][0];
}
int main()
{
ios::sync_with_stdio(0);
cin >> n >> m >> root;
tot = log2(n);
for(int i = 1;i < n;i ++)
{
int x,y;
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
bfs(root);
while (m --)
{
int x,y;
cin >> x >> y;
cout << lca(x,y) << endl;
}
return 0;
}