Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think your algorithm is mostly correct already, but with slight modifications it becomes trivial to implement.</p> <p>First, <em>every</em> negative edge has to be included in order to minimize the resulting weight. Next, calculate the number of connected components <code>c</code>. If <code>c=1</code>, you're done. Otherwise you need extra <code>c-1</code> positive edges.</p> <p>Now, while you were adding negative edges, consider this already as a Kruskal's algorithm process. Every negative edges may unite a couple of trees in the Kruskal's forest. However, you add the negative edge even if its ends belong to the same tree in the Kruskal's forest — unlike the usual Kruskal's algorithm where you only add those edges that unite two different trees.</p> <p>After this phase, you're left with a graph of <code>c</code> connected components (they may not be trees anymore). Now just continue the Kruskal's algorithm as usual. Process the positive edges in the increasing order, keeping track of the number of unions the you've made with positive edges. Once this number gets to <code>c-1</code>, you're done.</p> <p>By the way, all the process of Kruskal's algorithm can be implemented easily if you represent the forest as <a href="http://en.wikipedia.org/wiki/Disjoint-set_data_structure" rel="noreferrer">disjoint-set data structure</a>. It requires just a couple of lines of code to write, and after that it is trivial to keep track of the number of unions that were made.</p> <hr> <p>Some pseudocode follows:</p> <pre><code>sort(edges); c := n; for edge in edges: if edge.weight &lt; 0: if find(edge.firstEnd) != find(edge.secondEnd): --c; unite(edge.firstEnd, edge.secondEnd); else: if c == 1: break; if find(edge.firstEnd) != find(edge.secondEnd): unite(edge.firstEnd, edge.secondEnd); --c; </code></pre> <p>Here <code>unite</code> and <code>find</code> are the functions of disjoint-set data structure.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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