栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言实现并查集

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言实现并查集

通过压缩路径,优化find
通过小树合并大树,优化Union

#define SIZE 100
int S[SIZE];

void Init(int S[])
{
    for (int i = 0; i < S.length; i++)
    {
        S[i] = -1;
    }
}

//未优化的Find
int Find(int S[], int x)
{
    while (S[x] >= 0)
    {
        x = S[x];
    }
    return x;
}
//未优化的Union
void Union(int S[], int Root1, int Root2)
{
    if (Root1 == Root2)
        return;
    //小树并到大树
    S[Root2] = Root1;
}

//压缩路径优化,优化Find
int Find2(int S[], int x)
{
    int root = x;
    while (S[root] >= 0)
        root = S[root]; //找到根结点
    while (x != root)
    {
        int pre = S[x]; //找到前驱(父节点)
        S[x] = root;    //将结点挂在根结点下
        x = pre;        //父结点继续跟刚才一样操作
    }
}

//小树合并大树下进行优化,优化Union
void Union2(int S[], int Root1, int Root2)
{
    if (Root1 == Root2)
        return;
    if (S[Root2] > S[Root1]) // R2为小树,R1大树
    {
        S[Root1] += S[Root2];
        S[Root2] = Root1;
    }
    else
    {
        // R1为小树,R2大树
        S[Root2] += S[Root1];
        S[Root1] = Root2;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1018497.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号