18

Kruskal のアルゴリズムで使用する Disjoint Sets を実装しようとしていますが、それをどのように行うべきか、特に木の森を管理する方法を正確に理解するのに苦労しています。Wikipedia の Disjoint Sets の説明を読み、Introduction to Algorithms (Cormen et al) の説明を読んだ後、次のことを思いつきました。

    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 (x->rank == y->rank) {
                ++(y->rank);
            }
        }
    }

ただし、これは不完全であり、何かが欠けていると確信しています。

Introduction to Algorithms は、木の森があるべきだと述べていますが、この森の実際の実装については何の説明もしていません。CS 61B Lecture 31: Disjoint Sets ( http://www.youtube.com/watch?v=wSPAjGfDl7Q ) を見ましたが、ここで講師は配列のみを使用して、フォレストとそのすべてのツリーと値の両方を格納しています。私が述べたように、クラスの明示的な「ノード」タイプはありません。また、この手法を使用している他の多くの情報源 (複数のリンクを投稿することはできません) も見つけました。これはルックアップのために配列のインデックスに依存していることを除いて、喜んでこれを行います.int以外の型の値を保存したいので、何か他のものを使用する必要があります(std::mapが思い浮かびます)。

私がよくわからないもう 1 つの問題は、C++ を使用しているため、メモリの割り当てです。ポインターのツリーを保存しています。MakeSet 操作は次のようになります。 new DisjointSet::Node; . 現在、これらのノードには親へのポインターしかないため、ツリーの最下部を見つける方法がわかりません。ツリーをトラバースしてすべての割り当てを解除するにはどうすればよいですか?

このデータ構造の基本的な概念は理解していますが、実装については少し混乱しています。アドバイスや提案は大歓迎です、ありがとう。

4

10 に答える 10

3

決して完璧な実装ではありません (結局、私はそれを書きました!) が、これは役に立ちますか?

/***
 * millipede: DisjointSetForest.h
 * Copyright Stuart Golodetz, 2009. All rights reserved.
 ***/

#ifndef H_MILLIPEDE_DISJOINTSETFOREST
#define H_MILLIPEDE_DISJOINTSETFOREST

#include <map>

#include <common/exceptions/Exception.h>
#include <common/io/util/OSSWrapper.h>
#include <common/util/NullType.h>

namespace mp {

/**
@brief  A disjoint set forest is a fairly standard data structure used to represent the partition of
        a set of elements into disjoint sets in such a way that common operations such as merging two
        sets together are computationally efficient.

This implementation uses the well-known union-by-rank and path compression optimizations, which together
yield an amortised complexity for key operations of O(a(n)), where a is the (extremely slow-growing)
inverse of the Ackermann function.

The implementation also allows clients to attach arbitrary data to each element, which can be useful for
some algorithms.

@tparam T   The type of data to attach to each element (arbitrary)
*/
template <typename T = NullType>
class DisjointSetForest
{
    //#################### NESTED CLASSES ####################
private:
    struct Element
    {
        T m_value;
        int m_parent;
        int m_rank;

        Element(const T& value, int parent)
        :   m_value(value), m_parent(parent), m_rank(0)
        {}
    };

    //#################### PRIVATE VARIABLES ####################
private:
    mutable std::map<int,Element> m_elements;
    int m_setCount;

    //#################### CONSTRUCTORS ####################
public:
    /**
    @brief  Constructs an empty disjoint set forest.
    */
    DisjointSetForest()
    :   m_setCount(0)
    {}

    /**
    @brief  Constructs a disjoint set forest from an initial set of elements and their associated values.

    @param[in]  initialElements     A map from the initial elements to their associated values
    */
    explicit DisjointSetForest(const std::map<int,T>& initialElements)
    :   m_setCount(0)
    {
        add_elements(initialElements);
    }

    //#################### PUBLIC METHODS ####################
public:
    /**
    @brief  Adds a single element x (and its associated value) to the disjoint set forest.

    @param[in]  x       The index of the element
    @param[in]  value   The value to initially associate with the element
    @pre
        -   x must not already be in the disjoint set forest
    */
    void add_element(int x, const T& value = T())
    {
        m_elements.insert(std::make_pair(x, Element(value, x)));
        ++m_setCount;
    }

    /**
    @brief  Adds multiple elements (and their associated values) to the disjoint set forest.

    @param[in]  elements    A map from the elements to add to their associated values
    @pre
        -   None of the elements to be added must already be in the disjoint set forest
    */
    void add_elements(const std::map<int,T>& elements)
    {
        for(typename std::map<int,T>::const_iterator it=elements.begin(), iend=elements.end(); it!=iend; ++it)
        {
            m_elements.insert(std::make_pair(it->first, Element(it->second, it->first)));
        }
        m_setCount += elements.size();
    }

    /**
    @brief  Returns the number of elements in the disjoint set forest.

    @return As described
    */
    int element_count() const
    {
        return static_cast<int>(m_elements.size());
    }

    /**
    @brief  Finds the index of the root element of the tree containing x in the disjoint set forest.

    @param[in]  x   The element whose set to determine
    @pre
        -   x must be an element in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    @return As described
    */
    int find_set(int x) const
    {
        Element& element = get_element(x);
        int& parent = element.m_parent;
        if(parent != x)
        {
            parent = find_set(parent);
        }
        return parent;
    }

    /**
    @brief  Returns the current number of disjoint sets in the forest (i.e. the current number of trees).

    @return As described
    */
    int set_count() const
    {
        return m_setCount;
    }

    /**
    @brief  Merges the disjoint sets containing elements x and y.

    If both elements are already in the same disjoint set, this is a no-op.

    @param[in]  x   The first element
    @param[in]  y   The second element
    @pre
        -   Both x and y must be elements in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    */
    void union_sets(int x, int y)
    {
        int setX = find_set(x);
        int setY = find_set(y);
        if(setX != setY) link(setX, setY);
    }

    /**
    @brief  Returns the value associated with element x.

    @param[in]  x   The element whose value to return
    @pre
        -   x must be an element in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    @return As described
    */
    T& value_of(int x)
    {
        return get_element(x).m_value;
    }

    /**
    @brief  Returns the value associated with element x.

    @param[in]  x   The element whose value to return
    @pre
        -   x must be an element in the disjoint set forest
    @throw Exception
        -   If the precondition is violated
    @return As described
    */
    const T& value_of(int x) const
    {
        return get_element(x).m_value;
    }

    //#################### PRIVATE METHODS ####################
private:
    Element& get_element(int x) const
    {
        typename std::map<int,Element>::iterator it = m_elements.find(x);
        if(it != m_elements.end()) return it->second;
        else throw Exception(OSSWrapper() << "No such element: " << x);
    }

    void link(int x, int y)
    {
        Element& elementX = get_element(x);
        Element& elementY = get_element(y);
        int& rankX = elementX.m_rank;
        int& rankY = elementY.m_rank;
        if(rankX > rankY)
        {
            elementY.m_parent = x;
        }
        else
        {
            elementX.m_parent = y;
            if(rankX == rankY) ++rankY;
        }
        --m_setCount;
    }
};

}

#endif
于 2010-12-21T12:36:47.230 に答える
2

アルゴリズムについて話すことはできませんが、メモリ管理には通常、スマート ポインターと呼ばれるものを使用します。スマート ポインターは、それが指すものを解放します。共有所有権と単一所有権のスマート ポインター、および非所有権も取得できます。これらを正しく使用すると、メモリの問題が発生しないことが保証されます。

于 2010-12-21T12:09:56.450 に答える
0

次のコードは、パス圧縮による和集合と素性の集合を実装するために理解しやすいようです。

int find(int i)
{
    if(parent[i]==i)
    return i;
    else
    return parent[i]=find(parent[i]);
}
void union(int a,int b)
{
    x=find(a);y=find(b);
        if(x!=y)
        {
            if(rank[x]>rank[y])
            parent[y]=x;
            else
            {
            parent[x]=y;
            if(rank[x]==rank[y])
            rank[y]+=1;             
            }
        }
}
于 2015-07-19T21:07:44.023 に答える
0

このブログ記事は、パス圧縮を使用した C++ 実装を示しています: http://toughprogramming.blogspot.com/2013/04/implementing-disjoint-sets-in-c.html

于 2013-04-12T11:20:23.737 に答える
0

あなたの実装は問題ありません。ここで行う必要があるのは、結合されていないセット ノードの配列を保持して、それらに対して union/find メソッドを呼び出すことができるようにすることだけです。

Kruskal のアルゴリズムでは、グラフの頂点ごとに素集合のノードを 1 つ含む配列が必要です。次に、サブグラフに追加する次のエッジを検索するときに、find メソッドを使用して、それらのノードが両方ともサブグラフに既に含まれているかどうかを確認します。そうであれば、次のエッジに進むことができます。それ以外の場合は、そのエッジをサブグラフに追加し、そのエッジで接続された 2 つの頂点間で結合操作を実行します。

于 2012-01-24T20:55:23.823 に答える