#include<bits/stdc++.h>
using namespace std;
const int N = 500001;
int cnt,fa[N][22],n,m,s,head[N],depth[N];
struct qedge{
int to,next;
}edge[N*2];
void addedge(int x,int y){
edge[++cnt].to = y;
edge[cnt].next = head[x];
head[x] = cnt;
}
void dfs(int now,int fath){
fa[now][0] = fath,depth[now] = depth[fath] + 1;
for(int i = 1;i <= log2(depth[now]);i++){
fa[now][i] = fa[fa[now][i - 1]][i - 1];
}
for(int i = head[now];i;i = edge[i].next){
if(edge[i].to != fath){
dfs(edge[i].to,now);
}
}
}
int LCA(int x,int y){
if(depth[x] < depth[y]){
swap(x,y);
}
while(depth[x] > depth[y]){
x = fa[x][int(log2(depth[x] - depth[y]) - 1)];
}
if(x == y)return x;
for(int k = log2(depth[x]) - 1;k >= 0;k--){
if(fa[x][k] != fa[y][k]){
x = fa[x][k],y = fa[y][k];
}
}
return fa[x][0];
}
int main(){
cin>>n>>m>>s;
for(int i = 1;i < n;i++){
int a,b;
cin>>a>>b;
addedge(a,b);
addedge(b,a);
}
dfs(s,0);
for(int i = 1;i <= m;i++){
int a,b;
cin>>a>>b;
cout<<LCA(a,b)<<endl;
}
}
我都改的快和题解一样,就是不对?!