您的位置:首页 > 其它

并查集

2016-05-13 17:39 369 查看
并查集:
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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: