代码如下
#include<bits/stdc++.h>
using namespace std;
const int N=505000;
int tot=0;
queue<int> q;
int head[N],nxt[N],ver[N],edge[N];
int dep[N];
int dp[N][25];
int from,to,value;
void add(int x,int y){
ver[++tot]=y;
nxt[tot]=head[x];
head[x]=tot;
}
inline int read(){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0' && ch<='9')
x=x*10+ch-'0',ch=getchar();
return x*f;
}
void bdfs(int s){
q.push(s);
dep[s]=1;
while (!q.empty()){
int x=q.front();
q.pop();
for(int i=head[x];i;i=nxt[i]){
int y=ver[i];
if(dep[y]){
continue;
}
dep[y]=dep[x]+1;
dp[y][0]=x;
for(int j=1;j<=19;j++)
dp[y][j]=dp[dp[y][j-1]][j-1];
q.push(y);
}
}
}
int lca(int x,int y){
if(dep[x]>dep[y]){
swap(x,y);
}
for(int i=19;i>=0;i--){
if(dep[dp[y][i]]>=dep[x]){
y=dp[y][i];
}
}
if(x==y){
return x;
}
for(int i=19;i>=0;i--)
if (dp[x][i]!=dp[y][i]) {
x=dp[x][i];
y=dp[y][i];
}
return dp[x][0];
}
int main(){
int n,m,s;
cin>>n>>m>>s;
for(int i=1;i<=n-1;i++){
from=read();
to=read();
add(from,to);
add(to,from);
}
bdfs(s);
int a,b;
for(int i=1;i<=m;i++){
a=read();
b=read();
printf("%d\n",lca(a,b));
}
return 0;
}