大佬详解:https://blog.csdn.net/weixin_43826249/article/details/97756235 (以下代码基于这两个链接)
附加链式前向星存图原理详解: https://blog.csdn.net/LOOKQAQ/article/details/81304637
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
//边集
struct node{
ll to,next_s;
}edge[10001];
//fa[i][j]表示i的2的j次幂祖先
ll head[10001],in[10001],fa[10001][14],h[10001],lg[10001];
ll cnt,index;
//初始化
void init(){
memset(head,-1,sizeof(head));
memset(in,0,sizeof(in));
memset(h,0,sizeof(h));
memset(lg,0,sizeof(lg));
cnt=0;
}
//邻接表建立边
void add(ll from,ll to){
edge[cnt].to=to;
edge[cnt].next_s=head[from];//head[from]表示以from为起点的最后一条边
head[from]=cnt++;
}
//dfs求树的深度及幂次祖先
void dfs(ll u,ll f){
fa[u][0]=f;//fa[x][0]表示u的直接父亲为f
h[u]=h[f]+1;//深度差1
//求u的幂次祖先,u的2的i次幂祖先是u的2的i-1次幂祖先的2的i-1次幂祖先
//可以在深度的方面考虑一下,h[fa[u][i]]=h[x]+2^(i-1)+2^(i-1);
for(ll i=1;(1<<i)<=h[u];i++)fa[u][i]=fa[fa[u][i-1]][i-1];
for(ll i=head[u];i!=-1;i=edge[i].next_s){
dfs(edge[i].to,u);
}
}
//LCA
ll LCA(ll x,ll y){
//让x最深,注意越深h越大
if(h[x]<h[y]){
ll t=x;x=y;y=t;
}
//log(i)+1,,可以用数组求取,也可以用运算符直接求
// while(h[x]>h[y])x=fa[x][lg[h[x]-h[y]]-1];
while(h[x]>h[y])x=fa[x][ll(log(h[x]-h[y])/log(2))];
if(x==y)return x;//如果找到,直接返回
// for(ll i=lg[h[x]]-1;i>=0;i--){
// if(fa[x][i]!=fa[y][i]){
// x=fa[x][i];y=fa[y][i];
// }
// }
//从上往下找,第一下找到的肯定是根节点或者是根节点的直接孩子
for(ll i=log(h[x])/log(2);i>=0;i--){
if(fa[x][i]!=fa[y][i]){
//找到第一个非公共祖先同时往上提
x=fa[x][i];y=fa[y][i];
}
}
//最后找到的一定是公共祖先的直接孩子
return fa[x][0];
}
int main(){
ll t,n,x,y;
scanf("%lld",&t);
while(t--){
init();
scanf("%lld",&n);
for(int i=1;i<n;i++){
scanf("%lld %lld",&x,&y);
add(x,y);
in[y]++;//用来找根节点
}
for(int i=1;i<=n;i++){
if(in[i]==0){//找到根节点
index=i;break;
}
}
dfs(index,0);
//for(ll i=1;i<=n;i++)lg[i]=lg[i-1]+((1<<lg[i-1])==i);//数组求log(i)+1
scanf("%lld %lld",&x,&y);
printf("%lld\n",LCA(x,y));
}
return 0;
}