Search code examples
algorithmminimum-spanning-tree

Using a minimum spanning tree algorithm


Suppose I have a weighted non-directed graph G = (V,E). Each vertex has a list of elements.

We start in a vertex root and start looking for all occurances of elements with a value x. We wish to travel the least amount of distance (in terms of edge weight) to uncover all occurances of elements with value x.

The way I think of it, a MST will contain all vertices (and hence all vertices that satisfy our condition). Therefore the algorithm to uncover all occurances can just be done by finding the shortest path from root to all other vertices (this will be done on the MST of course).

Edit : As Louis pointed out, the MST will not work in all cases if the root is chosen arbitrarily. However, to make things clear, the root is part of the input and therefore there will be one and only one MST possible (given that the edges have distinct weights). This spanning tree will indeed have all minimum-cost paths to all other vertices in the graph starting from the root.


Solution

  • I don't think this will work. Consider the following example:

     x
     |
     3
     |
     y--3--root
     |     /
     5    3
     |   /
     |  /
      x
    

    The minimum spanning tree contains all three edges with weight 3, but this is clearly not the optimum solution.

    If I understand the problem correctly, you want to find the minimum-weight tree in the graph which includes all vertices labeled x. (That is, the correct answer would have total weight 8, and would be the two edges drawn vertically in this drawing.) But this does not include your arbitrarily selected root at all.

    I am pretty confident that the following variation on Prim's algorithm would work. Not sure if it's optimal, though.

    Let's say the label we are looking for is called L.

    1. Use an all-pairs shortest path algorithm to compute d(v, w) for all v, w.
    2. Pick some node labeled L; call this the root. (We can be sure that this will be in the result tree, since we are including all nodes labeled L.)
    3. Initialize a priority queue with the root initialized to 0. (The priority queue will consist of vertices labeled L, and their minimum distance from any node in the tree, including vertices not labeled L.)
    4. While the priority queue is nonempty, do the following:
      1. Pick out the top vertex in the queue; call it v, and its distance from the tree d.
      2. For each vertex w on the path from v to the tree, v inclusive, find the nearest L-labeled node x to w, and add x to the priority queue, or update its priority. Add w to the tree.