3

Given a weighted, connected, simple undirected graph G with weights of only 1 and 2 on each edge, find the MST of G in O(V+E). Any ideas?

Sorry for the phrasing of the question, I tried translating it as best as I could.

matanc1
  • 6,525
  • 6
  • 37
  • 57
  • Hint: change priority queue implementations. – David Eisenstat Jul 05 '13 at 19:13
  • Are you referring to the implementation of Kruskal using Union-Find or prim using Min Heaps? – matanc1 Jul 05 '13 at 19:27
  • Kruskal is `O(E * InverseAckermann(V))` since you can use counting sort for sorting in your case, which might as well be `O(E)` for all practical purposes. This should actually be better than `O(V+E)`, but if you want that, think about how you can adapt Prim's algorithm to take your small edge weights into consideration. – IVlad Jul 05 '13 at 19:54
  • What change were you thinking of? The main problem I have with Prim is that I need to find the vertex with the minimum "weight" on every iteration and that takes `O(V^2)` overall. What am I missing? – matanc1 Jul 05 '13 at 20:06
  • @Shookie - that's one implementation. The other involves using a heap and obtaining `O((E + V) log V)` time complexity. Think about how you can get rid of the `log V` factor. See the wikipedia entry. – IVlad Jul 05 '13 at 20:11

2 Answers2

4

In Prim's algorithm you need a way of storing active edges such that you can access and delete the edge with lowest weight.

Normally there are a wide range of weights and some kind of heap data structure is used to store the edges.

However, in this case, the weights are either 1 or 2, and so you can simply store the edges in 2 separate lists, one for edges with weight 1, and the second for edges with weight 2.

To find the edge with lowest weight you simply take one from the first list, unless it is empty, in which case you take an edge from the second list.

Accessing and deleting an element from a list is O(1) so Prim's algorithm will run in O(V+E).

Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75
1

Prim's algorithm computes a minimum spanning tree when edges have arbitrary weights.

Prim's algorithm works by doing a sort of breadth-first search, starting from some arbitrary node, and keeping the edges in a priority queue. It keeps extracting the lowest-weight edge and either discarding it without expanding the search (if the edge leads to a node already in the tree) or adding it to the result, marking its opposite node as in the tree, and expanding the search.

Done in the naive way I just explained, Prim's algorithm is dominated by the cost of enqueueing and dequeueing |E| edges into/outof the priority queue. Each enqueue/dequeue takes O(log |E|) time, so the total asymptotic cost is O(|E| log |E|) time or, more properly, O(|E| log |E| + |V|).

If we had some way to do those enqueues and dequeues in constant time, the total running time would be O(|E| + |V|)...

Craig Gidney
  • 17,763
  • 5
  • 68
  • 136