并查集

并查集:
1.将N个不同的元素分成一组不相交的集合。

2.开始时,每个元素就是一个集合,然后按规律将两个集合进行合并。

 

 

 

class UnionSet
{
public:
    UnionSet(size_t size)
        :_size(size)
    {
        _unionset.resize(size, -1);
    }

    void Combine(size_t pos1, size_t pos2)     //合并函数
    {
        int root1 = FindAncestor(pos1);
        int root2 = FindAncestor(pos2);
        _unionset[root1] += _unionset[root2];
        _unionset[root2] = root1;
    }

    int FindAncestor(size_t pos)     //寻找祖先节点的函数
    {
        while (_unionset[pos] >= 0)  //当某一元素为负数时说明,到了该集合的根节点了
        {
            pos = _unionset[pos];
        }
        return pos;
    }

protected:
    vector<int> _unionset;
    size_t _size;
};

 

posted @ 2016-05-13 17:39  _in_the_way  阅读(136)  评论(0编辑  收藏  举报