首页 > 其他 > 详细

并查集

时间:2020-01-14 23:34:40      阅读:82      评论:0      收藏:0      [点我收藏+]

并查集:find() + union()+ init()

寻找根节点 + 合并子树 + 初始化

 

#include <stdio.h>
#define MAX 100

using namespace std;

int father[MAX];    //自己的父亲 
int rank[MAX];        //

int find(int x){                    //寻找根节点 
    if(father[x]==x)    return x;
    else return    father[x]=find(father[x]);        //向上找父亲直到找到根节点 
}

void unite(int x, int y){            //合并两个子树 
    if(find(x) == find(y))    return;
    else{
        int x_root=find(x);
        int y_root=find(y);
        if(rank[x_root] > rank[y_root])            //按秩合并   //比较的是树根x_root和y_root的秩 ,不是x和y的 
            father[y_root]=x_root;
        else if(rank[y_root] > rank[x_root])
            father[x_root]=y_root;
        else{                            //两个树根的秩一样的话,任意合并到其中一个树根中,然后秩++ 
            father[x_root]=y_root;
            rank[y_root]++;
        }    
    }
}

void init(int n){            //初始化 
    for(int i=1;i<=n;i++){
        father[i]=i;        //自己是自己的父亲 
        rank[i]=0;            //初始高度为0 
    }
}

并查集

原文:https://www.cnblogs.com/shiliuxinya/p/12194489.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!