题目链接
1787: [Ahoi2008]Meet 紧急集合
Time Limit: 20 Sec Memory Limit: 162 MBSubmit: 2574 Solved: 1158
[ Submit][ Status][ Discuss]
Description
![](http://www.lydsy.com/JudgeOnline/images/17871.jpg)
Input
![](http://www.lydsy.com/JudgeOnline/images/17872.jpg)
Output
![](http://www.lydsy.com/JudgeOnline/images/17873.jpg)
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
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
Source
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const ll mod=1000000007;
const int MAXN=500000+100;
int head[MAXN],fa[MAXN][22],deep[MAXN];
bool vis[MAXN];
struct node
{
int to,next;
}edge[MAXN*2];
int tol=0;
void add(int u,int v){edge[++tol].to=v,edge[tol].next=head[u],head[u]=tol;}
int ab(int x){return x>=0? x:-x;}
//fa[x][i] 表示从结点x向上跳2^i的结点,dp[x][0]表示x的父节点
void dfs(int x)
{
vis[x]=1;
for(int i=1;i<=18;i++) //预处理
{
if(deep[x]<(1<<i)) break;
fa[x][i]=fa[fa[x][i-1]][i-1];
}
for(int i=head[x];i;i=edge[i].next)
{
if(vis[edge[i].to]) continue;
fa[edge[i].to][0]=x;
deep[edge[i].to]=deep[x]+1;
dfs(edge[i].to);
}
}
int lca(int x,int y)
{
if(deep[x]<deep[y]) swap(x,y); //使得x为深度大的
int d=deep[x]-deep[y]; //求深度差
for(int i=0;i<=18;i++)
if(d&(1<<i)) x=fa[x][i]; //使得x的深度与y的相同
if(x==y) return x; //若x与y已经相等,则说明y是x的祖先,返回x.
for(int i=18;i>=0;i--)
if(fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i]; //同时向上"跳";
return fa[x][0];
}
int dis(int x,int y){int t=lca(x,y);return deep[x]+deep[y]-2*deep[t];} //求树上两点距离
void solve(int x,int y,int z)
{
int u1=lca(x,y),u2=lca(x,z),u3=lca(y,z);
int t;
if(u1==u2) t=u3;
else if(u1==u3) t=u2;
else t=u1;
int ans=dis(x,t)+dis(y,t)+dis(z,t);
//注意不是ans=ab(deep[x]-deep[t])+ab(deep[y]-deep[t])+ab(deep[z]-deep[t]);
printf("%d %d\n",t,ans);
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
rep(i,1,n)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v),add(v,u);
}
dfs(1);
while(m--)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
solve(u,v,w);
}
return 0;
}