首页 > 其他 > 详细

并查集

时间:2016-05-13 18:39:41      阅读:239      评论:0      收藏:0      [点我收藏+]

并查集:
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;
};

 

并查集

原文:http://www.cnblogs.com/shihaochangeworld/p/5490199.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!