#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#define MAX 0x3f3f3f3f
using namespace std;
typedef long long LL;
int n,head[111111],cx,cy;
struct Edge
{
int to;
int next;
}edge[111111];
int cnt=0,father[111111],vis[111111];
int is_root[111111];
int root ;
int ans;
void add(int x,int y)
{
edge[cnt].to=y;
edge[cnt].next=head[x];
head[x]=cnt++;
}
int Find(int x)
{
while(x!=father[x])
x=father[x];
return x;
}
void union1(int x,int y)
{
int fx=Find(x),fy=Find(y);
if(fx!=fy)
father[fy]=fx;
}
void LCA(int x)
{
for(int i=head[x];i!=-1;i=edge[i].next)
{
int y=edge[i].to;
LCA(y);
union1(x,y);
vis[y]=1;
}
if(cx==x&&vis[cy]==1)
ans=Find(cy);
if(cy==x&&vis[cx]==1)
ans=Find(cx);
}
void slove()
{
cin >> cx >>cy;
LCA(root);
}
int main()
{
int t;
cin >>t;
while(t--)
{
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
memset(is_root,0,sizeof(is_root));
cin >>n;
for(int i=0;i<=n;i++)
father[i]=i;
for(int i=1; i<n; i++)
{
int x,y;
cin >> x >>y;
add(x,y);
is_root[y]=1;
}
for(int i=1;i<=n;i++)
{
if(is_root[i]==0)
{
root=i;
break;
}
}
slove();
cout <<ans <<endl;
}
return 0;
}
链式前向星(模板)
猜你喜欢
转载自blog.csdn.net/M_Y_Y_/article/details/81380612
今日推荐
周排行