并查集

并查集: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 
    }
}
posted @ 2020-01-14 22:50  北冥有鱼兮  阅读(153)  评论(0编辑  收藏  举报