(LCA离线)poj1330 M - Nearest Common Ancestors

#include"iostream"
#include"string.h"
using namespace std;
const int maxn=1e4+5;
int N;
struct Edge
{
    int t,next;
};
Edge E[maxn<<1];
int head[maxn];
int tot;
void AddEdge(int aa,int bb)
{
    E[++tot].t=bb;
    E[tot].next=head[aa];
    head[aa]=tot;
}
int color[maxn];
int ans,q1,q2;
int Fa[maxn];
int find(int x)
{
    if(x==Fa[x])return x;
    else return Fa[x]=find(Fa[x]);
}
void Tarjan(int u)
{
    Fa[u]=u;
    color[u]=1;

    if(u==q1)
    {
        if(color[q2]==1)ans=q2;
        else if(color[q2]==2)ans=find(q2);
    }
    if(u==q2)
    {
        if(color[q1]==1)ans=q1;
        else if(color[q1]==2)ans=find(q1);

    }
    for(int i=head[u];i!=-1;i=E[i].next)
    {
        int t=E[i].t;
        Tarjan(t);
        color[t]=2;
        Fa[t]=u;
    }
}
int main()
{
    int T;
    cin>>T;
    int TT=T;
    while(T--)
    {
        cin>>N;
        tot=0;
        ans=-1;
        int root=1;
        for(int i=1;i<=N;i++)Fa[i]=i;
        memset(color,0,sizeof(color));
        memset(head,-1,sizeof(head));
        for(int i=1;i<N;i++)
        {
            int t1,t2;
            cin>>t1>>t2;
            AddEdge(t1,t2);
            Fa[t2]=t1;
        }
        for(int i=1;i<=N;i++)root=Fa[root];
        cin>>q1>>q2;
        Tarjan(root);
        cout<<ans<<"\n";
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务