小编Isa*_*aac的帖子

在C++中实现不相交集(Union Find)

我正在尝试实现Disjoint Sets以用于Kruskal的算法,但我无法准确理解它应该如何完成,特别是如何管理树林.在阅读了维基百科关于不相交集的描述之后,在阅读了算法导论(Cormen等人)中的描述后,我得出以下结论:

    class DisjointSet
    {
    public:
        class   Node 
        {
        public:
            int         data;
            int         rank;

            Node*       parent;

            Node() : data(0), 
                     rank(0),
                     parent(this) { } // the constructor does MakeSet
        };

        Node*   find(Node*);
        Node*   merge(Node*, Node*); // Union
    };


    DisjointSet::Node*   DisjointSet::find(DisjointSet::Node* n)
    {
        if (n != n->parent) {
            n->parent = find(n->parent);
        }
        return n->parent;
    }

    DisjointSet::Node* DisjointSet::merge(DisjointSet::Node* x,
                                          DisjointSet::Node* y)
    {
        x = find(x);
        y = find(y);

        if (x->rank > y->rank) {
            y->parent = x;
        } else {
            x->parent = y;
            if …
Run Code Online (Sandbox Code Playgroud)

c++ disjoint-sets

17
推荐指数
1
解决办法
4万
查看次数

标签 统计

c++ ×1

disjoint-sets ×1