Konstantin Vyshetsky
unread,Nov 22, 2011, 3:18:09 PM11/22/11Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to fran...@gmail.com, danielk...@gmail.com, rj_crist...@yahoo.com, SJSUcmpe130
For anyone having a hard time with Kruskal's algorithm, and checking for cycles, I came up with something pretty cool.
We pretty much want to keep track of which vertices belong to which set. Every time we add an edge, the vertices will belong to whichever one is in a higher set. If they belong to same set we don't add the edge. On wikipedia they talked about using separate trees which sounds like an overkill for our purpose. My implementation is the following:
Simple struct with from, to, cost. Upon reading the file add each object into a vector. Make an array with size equal to maximum node. Set each index in the array equal to its position. Make another empty vector which will hold the Kruskal's edges.
The algorithm itself:
while the first vector is empty:
find the least cost edge in that vector and pop it.
set one int to the "from" value in that edge.
set second int to the "to" value in that edge.
while (array[from] is not equal to "from")
from = array[from]
while (array[to] is not equal to "to")
to = array[to]
if (from > to)
array[to] = from
add edge to output vector
else if(to > from)
array[from] = to
add edge to output vector
else - do nothing they belong to same set
When the first vector becomes empty, the output vector should contain all the valid edges.