简体   繁体   中英

How to get list of all elements from a 'Disjoint Sets'

In my problem, I have a bunch of Elements (Class Element). Say I have 1000 Elements. These Elements are initially un-associated which means they are in their own sets.

Later I need to use the union operation to merge some of these sets based of my program flow. I plan to use the boost library's disjoint_set ( http://www.boost.org/doc/libs/1_57_0/libs/disjoint_sets/disjoint_sets.html )

My question is how is it possible to list the Elements in a set given the representative of the set.

Is disjoint_set the best data structure for such a task. So should I look into using something else?

From your prose description, I get no information that the sets would actually form any graphs.

If all you want to do is associate Elements with a set, I'd suggest

std::map<ElementId, SetId>

(where ElementId could simply be Element* if you know the pointers stay valid).

If you also want to be able to query the inverse efficiently

bimap<Element, bimaps::multiset_of<SetId> >

would be a candidate. See a demonstration Live On Coliru ¹

#include <boost/range/iterator_range.hpp>
#include <boost/bimap/multiset_of.hpp>
#include <boost/bimap.hpp>
#include <iostream>

using namespace boost;

int main() {
    using Element = int; // for simplicity :)
    using SetId   = int;
    using Sets = bimap<Element, bimaps::multiset_of<SetId> >;

    Sets sets;
    sets.insert({ Element(1), 300 });
    sets.insert({ Element(2), 300 });
    sets.insert({ Element(3), 400 });
    sets.insert({ Element(4), 300 });

    // give us set #300
    for (auto& e : make_iterator_range(sets.right.equal_range(300)))
        std::cout << e.first << " - Element(" << e.second << ")\n";
}

Prints

300 - Element(1)
300 - Element(2)
300 - Element(4)

¹ Coliru seems down. Will add later

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM