首页 > 编程语言 > 详细

算法-并查集

时间:2020-04-01 22:46:58      阅读:73      评论:0      收藏:0      [点我收藏+]

查询两个节点是否连接,把两个节点相连,并查集

#ifndef UNIONFIND_UNIONFIND5_H
#define UNIONFIND_UNIONFIN5_H
#include <iostream>
#include <cassert>
using namespace std;

namespace UF5{
class UnionFind{
private:
    int* parent;
    int* rank; // rank[i]表示以i为根的集合表示的树的层数
    int count;
public:
    UnionFind(int count){
        parent = new int[count];
        rank = new int[count];
        this->count = count;
        for(int i=0;i<count;i++){
            parent[i] = i;//初始化情况下父节点为自己
            rank[i] =1;
        }
    }
    ~UnionFind(){
        delete[] parent; 
        delete[] rank;
    }
    int find(int p){
        assert(p>=0 && p<count);
        // while(p !=parent[p]){
        //     parent[p] = parent[parent[p]]; //路径压缩
        //     p = parent[p];
        // }
        // return p;
        if(p!=parent[p])
            parent[p] = find(parent[p]);
        return parent[p];
    }
    bool isConnected(int p,int q){
        return find(p) == find(q);
    }
    void unionElements(int p,int q){
        int pRoot = find(p);
        int qRoot = find(q);

        if(pRoot == qRoot)
            return;
        if(rank[pRoot] < rank[qRoot]){
            parent[pRoot] = qRoot;
        }
        else if(rank[qRoot] < rank[pRoot]){
            parent[qRoot] = pRoot;
        }else{
            parent[pRoot] = qRoot;
            rank[qRoot] +=1;
        }
        
        
    }
};
}

#endif

 

算法-并查集

原文:https://www.cnblogs.com/Erick-L/p/12616492.html

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