题目大意:给你一棵N个节点的数,M个询问,每次询问三个节点,让你求出一个集合点,使得三个点到该点和最小,输出这个点和最小和。
三个点两两求LCA。然后会至少有两个相同,不同的那个就是所求的点。距离和随便算算就出来了
#include<queue>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
struct line
{
int s,t;
int next;
}a[1000001];
int head[500001];
int edge;
inline void add(int s,int t)
{
a[edge].next=head[s];
head[s]=edge;
a[edge].s=s;
a[edge].t=t;
}
inline int abs(int x)
{
if(x<0)
x=-x;
return x;
}
bool v[500001];
int deep[500001];
int ans[500001][22];
inline void bfs(int r)
{
int i,j;
deep[r]=1;
for(i=0;i<=21;i++)
ans[r][i]=r;
queue <int>Q;
while(!Q.empty())
Q.pop();
Q.push(r);
v[r]=true;
while(!Q.empty())
{
int d=Q.front();
Q.pop();
for(i=head[d];i!=0;i=a[i].next)
{
int t=a[i].t;
if(!v[t])
{
v[t]=true;
Q.push(t);
deep[t]=deep[d]+1;
ans[t][0]=d;
int dt;
for(j=1;j<=21;j++)
{
dt=ans[t][j-1];
ans[t][j]=ans[dt][j-1];
}
}
}
}
}
inline int swim(int x,int y)
{
while(deep[x]!=deep[y])
{
int i=0;
while(deep[ans[y][i]]>deep[x])
i++;
if(i!=0)
i--;
y=ans[y][i];
}
return y;
}
inline int lca(int x,int y)
{
if(deep[x]>deep[y])
{
int t=x;
x=y;
y=t;
}
y=swim(x,y);
while(x!=y)
{
int i=0;
while(ans[x][i]!=ans[y][i])
i++;
if(i!=0)
i--;
x=ans[x][i];
y=ans[y][i];
}
return x;
}
int main()
{
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
int n,m;
scanf("%d%d",&n,&m);
int i;
int s,t;
for(i=1;i<=n-1;i++)
{
scanf("%d%d",&s,&t);
edge++;
add(s,t);
edge++;
add(t,s);
}
memset(v,false,sizeof(v));
bfs(1);
int x1,x2,x3;
int t1,t2,t3;
int sum;
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&x1,&x2,&x3);
t1=lca(x1,x2);
t2=lca(x2,x3);
t3=lca(x1,x3);
sum=0;
if(t1==t2&&t2==t3)
{
printf("%d ",t1);
sum=abs(deep[t1]-deep[x1])+abs(deep[t1]-deep[x2])+abs(deep[t1]-deep[x3]);
}
else if(t1==t2)
{
printf("%d ",t3);
sum=abs(deep[t3]-deep[x1])+abs(deep[t3]-deep[x3])+abs(deep[t2]-deep[x2])+abs(deep[t2]-deep[t3]);
}
else if(t1==t3)
{
printf("%d ",t2);
sum=abs(deep[t2]-deep[x2])+abs(deep[t2]-deep[x3])+abs(deep[t3]-deep[x1])+abs(deep[t3]-deep[t2]);
}
else if(t2==t3)
{
printf("%d ",t1);
sum=abs(deep[t1]-deep[x1])+abs(deep[t1]-deep[x2])+abs(deep[t2]-deep[x3])+abs(deep[t2]-deep[t1]);
}
printf("%d\n",sum);
}
return 0;
}