题目传送门
简单LCA
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=10000+100;
int dp[maxn][20],fa[maxn],du[maxn],in[maxn];
struct Edge{
int to,next;
}edge[maxn];
int head[maxn],tot;
int n;
void DFS(int u,int d,int f){
fa[u]=dp[u][0]=f;
du[u]=d;
for(int i=1;(1<<i)<=d;i++) dp[u][i]=dp[dp[u][i-1]][i-1];
for(int i=head[u];i!=-1;i=edge[i].next){
Edge e=edge[i];
int v=e.to;
if(v==f) continue;
DFS(v,d+1,u);
}
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
tot=0;
for(int i=1;i<=n;i++) head[i]=-1,in[i]=0;
for(int i=1;i<n;i++){
int u,v;
scanf("%d%d",&u,&v);
in[v]++;
edge[tot].to=v;
edge[tot].next=head[u];
head[u]=tot++;
}
memset(dp,0,sizeof(dp));
int node=0;
for(int i=1;i<=n && !node;i++) if(!in[i]) node=i;
DFS(node,0,-1);
int x,y;
scanf("%d%d",&x,&y);
if(du[x]<du[y]) swap(x,y);
int ci=du[x]-du[y];
for(int i=0;;i++){
if((1<<i)>ci) break;
if((ci>>i)&1) x=dp[x][i];
}
if(x==y){
printf("%d\n",x);
continue;
}
for(int i=15;i>=0;i--){
if(dp[x][i]!=dp[y][i]) x=dp[x][i],y=dp[y][i];
}
printf("%d\n",dp[x][0]);
}
}