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
  • 相关阅读:
    hdoj 2063 过山车
    hdoj 2112 HDU Today
    hdoj 1874 畅通工程续
    hdoj 2544 最短路
    sound of the genuine
    复习webpack的常用loader
    node-sass安装报错
    react-debug
    react-router 4v 路由嵌套问题
    React 中使用sass
  • 原文地址:https://www.cnblogs.com/Erick-L/p/12616492.html
Copyright © 2011-2022 走看看