模板:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int inf = 0x3f3f3f3f3f3f3f3f;
const int N = 2e5+5;
vector<int>g[N];
int n,q;
int dep[N];
int fa[N][35];
int lca(int x,int y){
//让x的深度更深
if(dep[x]<dep[y])swap(x,y);
//保持x的深度不超过y
for(int i=31;i>=0;i--){
if(dep[fa[x][i]]>=dep[y])x=fa[x][i];
}
if(x==y)return x;
for(int i=31;i>=0;i--){
if(fa[x][i]!=fa[y][i]){
x=fa[x][i];
y=fa[y][i];
}
}
return fa[x][0];
}
void dfs(int x,int p){
dep[x]=dep[p]+1;//更新dep
fa[x][0]=p;
for(int i=1;i<=31;i++){//循环更新fa
fa[x][i]=fa[fa[x][i-1]][i-1];
}
for(const auto &y:g[x]){
if(y==p)continue;
dfs(y,x);
}
}
void solve(){
cin>>n;
for(int i=1;i<n;i++){
int x,y;cin>>x>>y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs(1,0);
cin>>q;
while(q--){
int x,y;cin>>x>>y;
cout<<lca(x,y)<<"\n";
}
return;
}
signed main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t=1;
while(t--){
solve();
}
return 0;
}