题目
思路
显然的LCA
code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<cmath>
using namespace std;
int fa[500010][27],head[500010],c[500010],x,y,z;
struct f{
int to,net;
} a[1000020];
int n,m;
void dfs(int x,int f)
{
fa[x][0]=f;
c[x]=c[f]+1;
for (int j=1;(1<<j)<=c[x];j++)
{
fa[x][j]=fa[fa[x][j-1]][j-1];
}
for (int i=head[x];i;i=a[i].net)
{
if (a[i].to!=f) dfs(a[i].to,x);
}
return;
}
int k=1;
void add(int u,int v)
{
a[k].to=v;
a[k].net=head[u];
head[u]=k++;
return;
}
int LCA(int x,int y)
{
if (c[x]>c[y]) swap(x,y);
for (int i=20;i>=0;i--)
{
if (c[x]<=c[y]-(1<<i)) y=fa[y][i];
}
if (x==y) return x;
for (int i=20;i>=0;i--)
{
if (fa[x][i]==fa[y][i]) continue;
else x=fa[x][i],y=fa[y][i];
}
return fa[x][0];
}
long long ans;
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
}
dfs(1,0);
while (m--)
{
scanf("%d%d%d",&x,&y,&z);
int xx=LCA(x,y),yy=LCA(y,z),zz=LCA(x,z);
if (xx==yy) printf("%d ",zz);
else if (yy==zz) printf("%d ",xx);
else if (zz==xx) printf("%d ",yy);
ans=c[x]+c[y]+c[z]-c[xx]-c[yy]-c[zz];
printf("%lld\n",ans);
}
return 0;
}