https://www.luogu.com.cn/problem/P3379
#include<bits/stdc++.h>
using namespace std;
const int N=500009;
int n,f[N][20],t,d[N],m,root;
vector<int>w[N];
void bfs() {
queue<int>q;
memset(d,0,sizeof(d));
d[root]=1,q.push(root);
while(q.size()) {
int x=q.front(),si;
q.pop();
si=w[x].size();
for(int i=0; i<si; i++) {
int y=w[x][i];
if(d[y])
continue;
d[y]=d[x]+1;
f[y][0]=x;
for(int j=1; j<=t; j++)
f[y][j]=f[f[y][j-1]][j-1];
q.push(y);
}
}
}
int query(int x,int y) {
if(d[x]>d[y])
swap(x,y);
for(int i=t; i>=0; i--)
if(d[f[y][i]]>=d[x])
y=f[y][i];
if(x==y)
return x;
for(int i=t; i>=0; i--)
if(f[x][i]!=f[y][i])
x=f[x][i],y=f[y][i];
return f[x][0];
}
int main() {
scanf("%d%d%d",&n,&m,&root);
t=(int)(log(n)/log(2))+1;
for(int i=1; i<=n-1; i++) {
int x,y;
scanf("%d%d",&x,&y);
w[x].push_back(y),w[y].push_back(x);
}
bfs();
while(m--){
int x,y;
scanf("%d%d",&x,&y);
cout<<query(x,y)<<endl;
}
return 0;
}