求重合长度的一个小trick:
Len:A->B与Len:B->C的共同路径长为 (Length(AB)+length(BC)-length(AC))/2 对于求length(AB):即其1+|dep[lca(a,b)]-dep[a]|+|dep[lca(a,b)]-dep[b]| 至于求lca,倍增树剖tarjan皆可 因为是点权,所以最后要+1
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=3e5+100;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL siz[maxn],fa[maxn],dep[maxn],son[maxn];
LL top[maxn];
vector<LL>g[maxn];
void predfs(LL u,LL father){
siz[u]=1;
dep[u]=dep[father]+1;
fa[u]=father;
for(LL i=0;i<g[u].size();i++){
LL v=g[u][i];
if(v==father) continue;
predfs(v,u);
siz[u]+=siz[v];
if(siz[v]>siz[son[u]]) son[u]=v;
}
}
void dfs(LL u,LL topx){
top[u]=topx;
if(son[u]==0) return;///叶子节点
dfs(son[u],topx);///先处理重儿子
for(LL i=0;i<g[u].size();i++){
LL v=g[u][i];
if(v==fa[u]||v==son[u]) continue;
dfs(v,v);
}
}
LL lca(LL u,LL v){
while(top[u]!=top[v]){
if(dep[top[u]]<dep[top[v]]){
swap(u,v);
}
u=fa[top[u]];
}
return dep[u]<dep[v]?u:v;
}
int main(void)
{
///cin.tie(0);std::ios::sync_with_stdio(false);
LL n,m,root,test;n=read();m=read();test=read();
for(LL i=1;i<n;i++){
LL u,v;u=read();v=read();
g[u].push_back(v);g[v].push_back(u);
}
predfs(1,0);
dfs(1,1);
while(m--){
LL A,B,C;A=read();B=read();C=read();
LL s1=lca(A,B);LL s2=lca(C,B);LL s3=lca(A,C);
LL len1=1+abs(dep[s1]-dep[A])+abs(dep[s1]-dep[B]);
LL len2=1+abs(dep[s2]-dep[B])+abs(dep[s2]-dep[C]);
LL len3=1+abs(dep[s3]-dep[A])+abs(dep[s3]-dep[C]);
LL ans=(len1+len2-len3)/2+1;
cout<<ans<<"\n";
}
return 0;
}