#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
vector<int>tree[500010];
int sum[500010],fath[500010];
int jump[500010][22],lo;
void ycl(int n)
{
for(int p=1;p<=n;p++)
tree[p].push_back(-1);
}
void link(int x,int y)
{
tree[x].push_back(y);
tree[y].push_back(x);
}
void dfs(int u,int fa)
{
jump[u][0]=fa;
fath[u]=fa;
sum[u]=sum[fa]+1;
for(int p=1;p<lo;p++)jump[u][p]=jump[jump[u][p-1]][p-1];
for(int p=1;p<=tree[u].size()-1;p++)
{
if(tree[u][p]!=fa)
{
int k=tree[u][p];
dfs(k,u);
}
}
}
int lca(int a,int b)
{
if(a==b)return a;
if(sum[a]<sum[b])swap(a,b);
for(int p=lo;p>=0;p--)
if(sum[jump[a][p]]>=sum[b])a=jump[a][p];
if(a==b)return a;
for(int p=lo;p>=0;p--)
if(jump[a][p]!=jump[b][p])a=jump[a][p],b=jump[b][p];
return jump[a][0];
}
int main()
{
int n,m,root;
lo=20;
cin>>n>>m>>root;
ycl(n);
for(int p=1,x,y;p<=n-1;p++)
cin>>x>>y,link(x,y);
dfs(root,root);
int a,b;
for(int p=1;p<=m;p++)
cin>>a>>b,cout<<lca(a,b)<<endl;
}
吸氧都不行求优化/kk