zoukankan      html  css  js  c++  java
  • 并查集

    class Union_Find_Set {
    public:
        int setSize;
        vector<int> father;
        Union_Find_Set(int x) {
            setSize = x;
            father = vector<int>(setSize, 0);
            clear();
        }
        void clear() {
            for (int i = 0; i < setSize; i++) {
                father[i] = i;
            }
        }
        void resetFather(vector<int> * v) {
            for (auto it : (*v)) {
                if (it >= setSize) continue;
                father[it] = it;
            }
        }
        int getFather(int x) {
            int ret = x, tmp;
            while (ret != father[ret]) {
                ret = father[ret];
            }
            while (x != father[x]) {
                tmp = father[x];
                father[x] = ret;
                x = tmp;
            }
            return ret;
        }
        bool merge(int a, int b) {
            a = getFather(a);
            b = getFather(b);
            if (a == b) return false;
            father[a] = b;
            return true;
        }
        int countRoot() {
            int ret = 0;
            for (int i = 0; i < setSize; i++) {
                if (father[i] = i) {
                    ret++;
                }
            }
            return ret;
        }
    };
    View Code

    int getFather(int x) 获得节点x的颜色

    bool merge(int a, int b) 将与节点a颜色相同的节点染成节点b的颜色,并返回染色前节点ab颜色是否相同

    int countRoot() 当前并查集中颜色的数量

    void clear(int x) 重置前x个节点的状态

  • 相关阅读:
    setTimeOut与循环闭包问题
    ES6----class用法
    JS------对象的继承方式
    JavaScript对象 -构建
    nodejs异步---Async
    mongdb位置索引
    mongodb 索引3
    mongod 索引2
    mongodb 索引1
    3 C++数据类型
  • 原文地址:https://www.cnblogs.com/dramstadt/p/6187141.html
Copyright © 2011-2022 走看看