Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, all you do is test whether the two nodes have the same root. If you use path compression when you build your graph, this turns out to be very fast.</p> <hr> <blockquote> <p>I think it is because I am trying to incorporate it into an implementation of Kruskal's algorithm with it. After I have found all connected components, I want to sort output something that will denote each disjoint set from each disjoint set. Sorry to bother you so much but if possible might you have any psuedo code to explain what you mean?</p> </blockquote> <p>The sets are already identified by a common root node. <strong>After you have done all your unions</strong>, each unique set will have a single root. So you then run through each node and call <code>Find</code> on it. How about this:</p> <pre><code>typedef std::list&lt; Node* &gt; TNodeList; typedef std::map&lt; Node*, TNodeList &gt; TSetMap; TSetMap mysets; // Assuming you have nodes stored in the list type I declared above... for( TNodeList::iterator n = nodes.begin(); n != nodes.end(); n++ ) { Node *thisnode = *n; Node *rootnode = Find(thisnode); // Add to list for root. Using the [] operator on map will create a new // list if none exists for that node. mysets[rootnode].push_back(thisnode); } </code></pre> <p>Now you have a map containing all your sets as individual lists, and you can do what you like...</p> <pre><code>std::cout &lt;&lt; "Number of disjoint sets: " &lt;&lt; mysets.size() &lt;&lt; std::endl; int count = 0; for( TSetMap::iterator s = mysets.begin(); s != mysets.end(); s++ ) { TNodeList &amp; nl = s-&gt;second; std::cout &lt;&lt; "Set " &lt;&lt; ++count &lt;&lt; " contains " &lt;&lt; nl.size() &lt;&lt; " nodes\n"; } </code></pre> <p>To make all these calls to <code>Find</code> efficient, you should implement path compression in your <code>Union</code> function.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload