(LCA离线)poj1330 M - Nearest Common Ancestors

本文介绍了一个使用C++实现的图遍历算法——Tarjan算法,并结合并查集进行路径压缩优化,用于解决特定类型的图问题。通过实例展示了如何构建图结构、添加边以及如何利用Tarjan算法寻找特定节点之间的连接关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值