您的位置:首页 > 其它

一些灵巧的求并算法

2015-10-13 11:54 211 查看
class DisjSets
{
public:
explicit DisjSets(int numElements);
int find(int x)const;
int find(int x);
void unionSets(int root1, int root2);
private:
vector<int> s;
};

DisjSets::DisjSets(int numElements) : s(numElements)
{
for (int i = 0; i < s.size(); i++)
s[i] = -1;
}

//下面是将两个集合并
void DisjSets::unionSets(int root1, int root2)
{
s[root2] = root1;
}

//下面是寻找一个元素所在的集合
int DisjSets::find(int x) const
{
if (s[x] < 0)
return x;
else
return find(s[x]);
}


//下面的是并集的一个变种,用于控制树的高度以及节点数量
void DisjSets::unionSets(int root1, int root2)
{
if (s[root2] < s[root1])    //root2 is deeper
s[root1] = root2;
else
{
if (s[root1] == s[root2])
s[root1]--;            //如果深度相同的话,再是root1的深度变得更深一点
s[root2] = root1;        //然后再让root2指向root1
}
}


//对上述并集程序使用了路径压缩之后,体现在find程序上的变化
int DisjSets::find(int x)const
{
if (s[x] < 0)
return x;
else
return s[x] = find(s[x]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: