#include <iostream>

template<int size>
class disj_set {
public:
    disj_set(){
        for (int i=0; i<size; i++) {
            father[i] = i;
            rank[i] = 0;
        }
    }

    int find_set(int x) {
        if (father[x] != x)
            father[x] = find_set(father[x]);

        return father[x];
    }

    int find_quick(int x) {
        int fb = -1;
        int fx = x;
        
        while (father[fx] != fx) 
            fx = father[fx];     

        while (father[x] != x){
            fb = father[x];
            father[x] = fx;
            x = fb;
        }

        return fx;
    }

    //void union_set(int x, int y) {
    //    int fx = find_set(x);
    //    int fy = find_set(y);
    //    if (fx != fy) 
    //        father[fy] = fx;
    //}

    void union_set(int x, int y) {
        int fx = find_set(x);
        int fy = find_set(y);
        if (fx == fy) 
            return;

        if (rank[x] > rank[y])
            father[fy] = fx;
        else {
            father[fx] = fy;
            if (rank[fx] == rank[fy])
                rank[fy]++;
        }
    }

private:
    int father[size];
    int rank[size];
};

int main() {
    disj_set<5> s1;
    s1.find_set(0);
    s1.find_set(1);
    s1.find_set(2);
    s1.find_set(3);
    s1.find_set(4);
    s1.union_set(1,3);
    s1.find_set(2);
    s1.find_set(4);
    s1.union_set(0,1);
    s1.union_set(1,2);
    s1.union_set(2,3);
    s1.union_set(3,4);
}

 

 posted on 2013-08-18 10:57  晴朗蝈蝈  阅读(123)  评论(0编辑  收藏  举报