【题目描述】
给定一棵 n 个点的树,Q 个询问,每次询问点 x 到点 y 两点之间的距离。
【输入】
第一行一个正整数 n,表示这棵树有 n 个节点;
接下来 n−1 行,每行两个整数 x,y表示 x,y 之间有一条连边;
然后一个整数 Q,表示有 Q 个询问;
接下来 Q 行每行两个整数 x,y 表示询问 x 到 y 的距离。
【输出】
输出 Q 行,每行表示每个询问的答案。
【输入样例】
6
1 2
1 3
2 4
2 5
3 6
2
2 6
5 6
【输出样例】
3
4
【提示】
数据范围与提示:
对于全部数据,1≤n≤105,1≤x,y≤n
#include<bits/stdc++.h>
#define read() freopen("input.txt","r",stdin);
#define write() freopen("output.txt","w",stdout);
using namespace std;
const int maxn = 1e5+10;
int first[maxn*2],go[maxn*2],next[maxn*2],tot=0;
int deep[maxn],f[maxn][21];
void add(int u,int v){
next[++tot]=first[u];first[u]=tot;go[tot]=v;
next[++tot]=first[v];first[v]=tot;go[tot]=u;
}
void deal_first(int u,int father){
deep[u]=deep[father]+1;
for( int i=0; i<=19; i++ ){
f[u][i+1]=f[f[u][i]][i];
}
for( int e=first[u]; e; e=next[e]){
int v=go[e];
if(v==father) continue;
f[v][0]=u;
deal_first(v,u);
}
}
int lca(int x,int y){
if(deep[x]<deep[y]) swap(x,y);
for( int i=20; i>=0; i-- ){
if(deep[f[x][i]]>=deep[y]) x=f[x][i];
if(x==y) return x;
}
for( int i=20; i>=0; i-- ){
if(f[x][i]!=f[y][i]){
x=f[x][i];y=f[y][i];
}
}
return f[x][0];
}
int dist(int x,int y){
return deep[x]+deep[y]-2*deep[lca(x,y)];
}
int n,m,x,y;
int main()
{
read();write();
cin>>n;
for( int i=1; i<n; i++ ){
scanf("%d %d",&x,&y);
add(x,y);
}
deal_first(1,0);
cin>>m;
for( int i=0; i<m; i++ ){
scanf("%d %d",&x,&y);
printf("%d\n",dist(x,y));
}
return 0;
}