Here I am using Tarjan: If Tarjan is used, we need to know the root node of the tree. This question is not mentioned, but we can judge the root node based on the input level equal to 0; the main idea of Tarjan is DFS and merging;
Tarjan: To be supplemented
#include<cstdio>#include<string.h>#include<algorithm>#include<vector>#include<stdlib.h>#include<cmath>#include<queue>#include<set>#include<map>#include<list>using namespace std;const int N=10005;vector<int>M[N],Q[N];bool vis[N];int father[N],ance[N],in[N];int ex,ey;int find(int x){return x==father[x]?x:father[x]=find(father[x]);}void Union(int x,int y){ father[find(x)]=y;}void dfs(int u){ance[u]=u;int dd=M[u].size();for(int i=0;i<dd;++i){dfs(M[u][i]);Union(u,M[u][i]);ance[find(u)]=u;}vis[u]=1;dd=Q[u].size();for(int i=0;i<dd;i++){if(vis[Q[u][i]]==1){printf("%d\n",ance[find(Q[u][i])]);return;}}}int main(){int t,n,u,v;scanf("%d",&t);while(t--){scanf("%d",&n);for(int i=0;i<=n;i++){in[i]=0;father[i]=i;vis[i]=false;ance[i]=0;M[i].clear();Q[i].clear();}for(int i=1;i<n;i++){scanf("%d%d",&u,&v);M[u].push_back(v);in[v]++;}scanf("%d%d",&u,&v);Q[u].push_back(v);Q[v].push_back(u);for(int i=1;i<=n;i++)if(in[i]==0){dfs(i);break;}}return 0;}