并查集模板

这篇博客详细介绍了并查集这一数据结构,并提供了初始化、查找根节点(路径压缩)和合并操作的代码实现。通过两个POJ在线判题示例,展示了并查集在解决实际问题中的应用,帮助读者理解其在图论和连接查询中的作用。
摘要由CSDN通过智能技术生成

并查集模板

并查集模板

代码:



int father[N];//定义father数组,存储父亲节点


void init(int x)//初始化father数组
{
    for(int i=1;i<=x;i++)
        father[i]=i;
}

//并查集的核心,查找祖宗节点(根节点)
//路径优化版本是在查找的过程中将经过的结点都指向
//祖宗节点,在下一次查找到该节点时就只用查找一次
int find_father(int x)
{
    /*
    //递归
    if(x!=father[x])
        return find_father(father[x]);
    return x;
    */
    
    //递归版本 + 路径压缩
    if(x!=father[x])
        father[x]=find_father(father[x]);
    return father[x];
    
    /*
    //非递归
    while(x!=father[x])
        x=father[x];
    return x;
    
    */
    
    /*
    //非递归 + 路径压缩
    int a=x;
    while(x!=father[x])
        x=father[x];
    while(a!=father[a])
    {
        int b=a;
        a=father[a];
        father[b]=x;
    }
    return x;
    */
}

//将 a,b 合并到一个并查集中
void merge_(int a,int b)
{
    int fa=find_father(a);
    int fb=find_father(b);
    if(fa!=fb)
        father[fa]=fb;
        //father[fb]=fa; 无影响
}

例题:

1 poj 2236 http://poj.org/problem?id=2236

2 poj 1703 http://poj.org/problem?id=1703

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值