Description:
Input
Output
Sample Input
6 4
1 2
2 3
2 4
4 5
5 6
4 5 6
6 3 1
2 4 4
6 6 6
Sample Output
5 2
2 5
4 1
6 0
HINT
/**************************************************************
Problem: 1787
User: 不告诉你!
Language: C++
Result: Accepted
Time:3684 ms
Memory:73556 kb
****************************************************************/
#include<iostream>
#include<cstdio>
using namespace std;
int n,m,cou;
int mem[500010],vis[500010],depth[500010],fa[500010][30];
struct node
{
int to,next;
}edge[1000010];
void build(int u,int v)
{
cou++;
edge[cou].to=v;
edge[cou].next=mem[u];
mem[u]=cou;
}
void dfs(int x)
{
vis[x]=1;
for(int i=1;i<=18;i++)
{
if(depth[x]<(1<<i))
break;
fa[x][i]=fa[fa[x][i-1]][i-1];
}
for(int i=mem[x];i;i=edge[i].next)
{
if(vis[edge[i].to])
continue;
depth[edge[i].to]=depth[x]+1;
fa[edge[i].to][0]=x;
dfs(edge[i].to);
}
}
int LCA(int x,int y)
{
if(depth[x]<depth[y])
swap(x,y);
int dif=depth[x]-depth[y];
for(int i=0;i<=18;i++)
if(dif&(1<<i))
x=fa[x][i];
for(int i=18;i>=0;i--)
if(fa[x][i]!=fa[y][i])
{
x=fa[x][i];
y=fa[y][i];
}
if(x==y)
return x;
return fa[x][0];
}
void get_ans(int x,int y,int z)
{
int t1,t2,t3;
t1=LCA(x,y);t2=LCA(y,z);t3=LCA(x,z);
int k1,k2,k3;
k1=LCA(t1,z);k2=LCA(t2,x);k3=LCA(t3,y);
int t,ans=233333333,dif;
dif=depth[x]+depth[y]-depth[t1]+depth[z]-2*depth[k1];
if(dif<ans)
{
ans=dif;t=t1;
}
dif=depth[y]+depth[z]-depth[t2]+depth[x]-2*depth[k2];
if(dif<ans)
{
ans=dif;t=t2;
}
dif=depth[x]+depth[z]-depth[t3]+depth[y]-2*depth[k3];
if(dif<ans)
{
ans=dif;t=t3;
}
printf("%d %d\n",t,ans);
return;
}
int main()
{
scanf("%d%d",&n,&m);
int u,v;
for(int i=1;i<n;i++)
{
scanf("%d%d",&u,&v);
build(u,v);build(v,u);
}
dfs(1);
for(int i=1;i<=m;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
get_ans(x,y,z);
}
return 0;
}