题意:
思路:
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 3e5 + 10;
struct Edge{
int to,nex;
}e[N << 1];
int head[N],dep[N],fa[N][20],idx,n,A,B;
void add_edge(int u,int v){
e[idx].to = v;
e[idx].nex = head[u];
head[u] = idx++;
}
void dfs(int u,int f){
dep[u] = dep[f] + 1;
fa[u][0] = f;
for(int i = head[u];~i;i = e[i].nex){
int v = e[i].to;
if(v == f) continue;
dfs(v,u);
}
}
void init(){
for(int k = 1;(1<<k) <= n;k++){
for(int i = 1;i <= n;i++){
fa[i][k] = fa[fa[i][k-1]][k-1];
}
}
}
int lca(int u,int v){
if(dep[u] < dep[v]) swap(u,v);
if(dep[u] != dep[v]){
for(int i = 19;i >= 0;i--){
if(dep[fa[u][i]] >= dep[v]) u = fa[u][i];
}
}
if(u == v) return v;
for(int i = 19;i >= 0;i--){
if(fa[u][i] != fa[v][i]){
u = fa[u][i],v = fa[v][i];
}
}
return fa[u][0];
}
int dist(int u,int v){
return dep[u] + dep[v] - (dep[lca(u,v)] * 2);
}
int main(){
memset(head,-1,sizeof(head));
scanf("%d",&n);
for(int i = 1,u,v;i < n;i++){
scanf("%d%d",&u,&v);
add_edge(u,v);add_edge(v,u);
}
dfs(1,0);
init();
scanf("%d%d",&A,&B);
int q;scanf("%d",&q);
while(q--){
int u,v;scanf("%d%d",&u,&v);
int res = dist(u,v);
res = min(res,min(dist(u,B) + dist(A,v),dist(u,A) + dist(B,v)));
printf("%d\n",res);
}
return 0;
}