不相交集类

等价关系:自反性,对称性,传递性

class DisjSets//不相交集的类架构
{
public:
    explicit DisjSets(int numElements);
    int find(int x) const;
    int find(int x);
    void unionSets(int root1,int root2);
    void unionSets2(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;
}
void DisjSets::unionSets2(int root1,int root2)
{
    if( s[root2] < s[root1])
        s[root1] = root2;
    else
    {
        if(s[root1] == s[root2])
            s[root1]--;
        s[root2] = root1;
    }
}
int DisjSets::find(int x) const
{
    if(s[x] < 0)
        return x;
    else
        return find(s[x]);
}

灵巧求并算法:按大小求并,或者按高度求并

路径压缩:唯一变化就是返回的是 find 返回的值(与按大小求并完全兼容)

int DisjSets::find(int x) 
{
    if(s[x] < 0)
        return x;
    else
        return s[x] = find(s[x]);
}

应用:迷宫问题

posted @ 2012-10-07 14:18  xingoo  阅读(606)  评论(0编辑  收藏  举报