POJ1330 Nearest Common Ancestors

本文介绍了一种求解最近公共祖先(LCA)问题的算法实现,通过并查集的方法,在树形结构中找到两个节点的最近公共祖先。文章提供了一个完整的C++代码示例,包括初始化、查找与合并操作。

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

Lca 入门题
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
using namespace std;
int const MAXN = 10010;
int n,u,v;
vector <int> q[MAXN];
int father[MAXN],vis[MAXN],root[MAXN];
void Init(){
    for(int i = 0;i < MAXN;i++){
        q[i].clear();
        vis[i] = 0;
        root[i] = 1;
        father[i] = i;
    }
}
int  Find(int x){
    int y = x;
    while(y != father[y]){
        y = father[y];
    }
    while(x != father[x]){
        int temp = father[x];
        father[x] = y;
        x = temp;
    }
    return x;
}
void Union(int x,int y){
    int xx = Find(x);
    int yy = Find(y);
    if(xx == yy) return ;
    father[yy] = xx;
}
void Lca(int per){
    for(int i = 0;i < q[per].size();i++){
        Lca(q[per][i]);
        Union(per,q[per][i]);
    }
    vis[per] = 1;
    if(per == u && vis[v] == 1){
        printf("%d\n",Find(v));
        return ;
    }
    if(per == v && vis[u] == 1){
        printf("%d\n",Find(u));
        return ;
    }
}
int main(){
    int t;
    while(~scanf("%d",&t)){
        while(t--){
            Init();
            int n;
            scanf("%d",&n);
            for(int i = 1;i < n;i++){
                int a,b;
                scanf("%d%d",&a,&b);
                q[a].push_back(b);
                root[b] = 0;
            }
            scanf("%d%d",&u,&v);
            int s;
            for(int i = 1;i <= n;i++){
                if(root[i]){
                    s = i;
                    break;
                }
            }
            Lca(s);
        }
    }
    return 0;
}
/*
2
5
2 3
3 4
3 1
1 5
3 5
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值