LCA,对于每一个(x,y,z),两两求LCA得最优解或求出LCA不同于其他两组的那个为最优解。
code:
/**************************************************************
Problem: 1787
User: yekehe
Language: C++
Result: Accepted
Time:5212 ms
Memory:51604 kb
****************************************************************/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int read()
{
char c;while(c=getchar(),c<''||c>'');
int x=c-'';while(c=getchar(),c>=''&&c<='')x=(x<<)+(x<<)+c-'';
return x;
}
const int MAXN=;
int N,M;
int head[MAXN],to[MAXN<<],nxt[MAXN<<],cnt;
void add(int x,int y)
{
to[cnt]=y;
nxt[cnt]=head[x];
head[x]=cnt;
cnt++;
}
int D[MAXN];
int f[][MAXN];
void dfs(int now,int deep,int fa)
{
D[now]=deep;
f[][now]=fa;
for(int i=head[now];i!=-;i=nxt[i])
if(!D[to[i]])
dfs(to[i],deep+,now);
return ;
}
int Me;
int get(int x,int y)
{
if(D[x]<D[y])swap(x,y);
for(int i=;i>=;i--)
if(D[f[i][x]]>=D[y])x=f[i][x];
if(x==y)return x;
for(int i=;i>=;i--)
if(f[i][x]!=f[i][y])
x=f[i][x],y=f[i][y];
return f[][x];
}
int solve(int x,int y)
{
return D[x]+D[y]-(D[get(x,y)]<<);
}
int main(){
memset(head,-,sizeof head);
memset(nxt,-,sizeof nxt);
N=read(),M=read();
register int i,j;
for(i=;i<N;i++){
int x=read(),y=read();
add(x,y),add(y,x);
}
dfs(,,);
for(i=;i<=;i++)
for(j=;j<=N;j++)
f[i][j]=f[i-][f[i-][j]];
for(i=;i<=M;i++){
int x=read(),y=read(),z=read();
int a=get(x,y),b=get(y,z),c=get(x,z);
int dist=;
if(a==b)dist=c;else
if(b==c)dist=a;else
dist=b;
printf("%d %d\n",dist,solve(x,dist)+solve(y,dist)+solve(z,dist));
}
return ;
}