zoukankan      html  css  js  c++  java
  • 算法-并查集

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

    #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
  • 相关阅读:
    Dubbo框架——整体架构
    ie8不支持的数组方法
    前端面试问题
    Cookie和WebStorage的区别
    flex部局 API
    组合继承介绍
    克隆节点
    键盘事件
    js动态创建元素和删除
    js中的节点属性 和上下级访问关系
  • 原文地址:https://www.cnblogs.com/Erick-L/p/12616492.html
Copyright © 2011-2022 走看看